Home > Software engineering >  show based on array list component name Vuejs
show based on array list component name Vuejs

Time:11-23

I have a lot of component in my code and that was so long in the code, and I think that need to be more simple.
Is there somehow a way to make it like my example code?
To make component name called like that

<template>
  <div v-for="(ob,i) in list">
    <ob.componentName :title="ob.title"></ob.componentName>
  </div>  
  </template>
  
  <script>
  import componentA from "..."
  import componentB from "..."
  import componentC from "..."
  export default {
    components:{
       componentA,componentB,componentC
    },
    data() {
      return {
       list:[
           {title:"A" , componentName:"component-a"},
           {title:"B" , componentName:"component-b"},
           {title:"C" , componentName:"component-c"},
       ]
        
      };
    },
  }
  </script>

I have tried my example code, and of course that was error in that.
And try to googling and cannot find anything.

CodePudding user response:

You should use :is attribute to dynamically map the imported components.

<div v-for="(ob,i) in list">
  <component :is="ob.componentName" :title="ob.title"></component>
</div>
  • Related