VUE 3负载组件从字符串动态
尝试基于字符串动态负载组件。
应该看起来像这样:
<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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将组件添加到数组中,而无需定义为字符串
const constonents = [barchart]
:Add the component to the array without defining as string
const components = [BarChart]
: