VUE 3负载组件从字符串动态

发布于 2025-01-31 05:42:03 字数 647 浏览 0 评论 0原文

尝试基于字符串动态负载组件。

应该看起来像这样:

<component v-for="component in components" :is="eval(component)" />

但是不幸的是,这是行不通的。

我目前正在使用的解决方法正在创建一个返回组件的函数:

<script setup>
import BarChart from '@/components/BarChart.vue'

const components = ['BarChart']

const stringToComponent = component => {
  return eval(component)
}
</script>

<template>
  <component v-for="component in components" :is="stringToComponent(component)" />
</template>

为什么调用eval不正常工作,是否有可能避免创建函数?

Trying to dynamic load components based on a string.

Should look something like this:

<component v-for="component in components" :is="eval(component)" />

But unfortunately this doesn't work.

The workaround I'm using for now is creating a function returning the component:

<script setup>
import BarChart from '@/components/BarChart.vue'

const components = ['BarChart']

const stringToComponent = component => {
  return eval(component)
}
</script>

<template>
  <component v-for="component in components" :is="stringToComponent(component)" />
</template>

Why is calling eval directly not working and is it possible to avoid creating a function?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

荒岛晴空 2025-02-07 05:42:03

将组件添加到数组中,而无需定义为字符串const constonents = [barchart]

<script setup>
import BarChart from '@/components/BarChart.vue'

const components = [BarChart]

</script>

<template>
  <component v-for="component in components" :is="component" />
</template>

Add the component to the array without defining as string const components = [BarChart] :

<script setup>
import BarChart from '@/components/BarChart.vue'

const components = [BarChart]

</script>

<template>
  <component v-for="component in components" :is="component" />
</template>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文