简体   繁体   中英

Vue 3 load component dynamically from string

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?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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