[Vuejs]-Can I create a component with a loop in vue js? Is there a way to make it recognized as html tags?

0👍

You’re looking for dynamic components. You can render components by their names.

Vue.component('yellow', {
  template: '#yellow',
  name: 'Yellow'
})

Vue.component('red', {
  template: '#red',
  name: 'Red'
})

Vue.component('green', {
  template: '#green',
  name: 'Green'
})

Vue.component('app-list', {
  template: '#list',
  name: 'app-list',
   data (){
     return {
       componentLists : [
         {  
           isAppend : true,
           name : 'yellow'
          },
          {  
           isAppend : false,
           name : 'red'
          },
          {  
           isAppend : true,
           name : 'green'
          }
        ]
      };
    },
})

new Vue({
  el: "#app",
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
  <app-list />
</div>

<template id="list">
  <div>
    <div v-for="(component, index) in componentLists" :key="index">
      <component :is="component.name"></component>
    </div>
  </div>
</template>

<template id="yellow">
  <span>Yellow Component</span>
</template>

<template id="red">
  <span>Red Component</span>
</template>

<template id="green">
  <span>Green Component</span>
</template>

Leave a comment