Vue 3 load component dynamically from string

Viewed 344

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?

1 Answers

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>

Related