繁体   English   中英

Vue 3 从字符串动态加载组件

[英]Vue 3 load component dynamically from string

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

应该是这个样子:

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

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

我现在使用的解决方法是创建一个 function 返回组件:

<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 不起作用,是否可以避免创建 function?

将组件添加到数组而不定义为字符串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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM