2

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 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

4 Comments

:in was a typo. I'm using :is but it expects a component not a string.
@ErikAlserda please check my edited answer
My example is pseudo code, the array of components are fetched from a API so it will be a array of strings.
what about import {h} from 'vue' and use h instead of eval

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.