Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue 3: component `:is` in for loop fails

Tags:

vue.js

vuejs3

I'm trying to loop over a list of component described by strings (I get the name of the component from another , like const componentTreeName = ["CompA", "CompA"].

My code is a simple as:

<script setup>
    import CompA from './CompA.vue'
    import { ref } from 'vue'

    // I do NOT want to use [CompA, CompA] because my inputs are strings
    const componentTreeName = ["CompA", "CompA"]
</script>

<template>
  <h1>Demo</h1>
  <template v-for="compName in componentTreeName">
    <component :is="compName"></component>
  </template>
</template>

Demo here

EDIT

I tried this with not much success.

like image 281
tobiasBora Avatar asked Jan 31 '26 02:01

tobiasBora


1 Answers

When using script setup, you need to reference the component and not the name or key.

To get it to work, I would use an object where the string can be used as a key to target the component from an object like this:

<script setup>
    import CompA from './CompA.vue'
    import { ref } from 'vue'
    const components = {CompA};

    // I do NOT want to use [CompA, CompA] because my inputs are strings
    const componentTreeName = ["CompA", "CompA"]
</script>

<template>
  <h1>Demo</h1>
  <template v-for="compName in componentTreeName">
    <component :is="components[compName]"></component>
  </template>
</template>

To use a global component, you could assign components by pulling them from the app context. But this would require the app context to be available and the keys known.

example:

import { app } from '../MyApp.js'
const components = {
  CompA: app.component('CompA')
}

I haven't tested this, but this might be worth a try to check with getCurrentInstance

import { ref,getCurrentInstance } from 'vue'
const components = getCurrentInstance().appContext.components;
like image 152
Daniel Avatar answered Feb 02 '26 22:02

Daniel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!