[Vuejs]-How to pull different components into divs with v-for?

0๐Ÿ‘

You can use v-html directive: https://v2.vuejs.org/v2/guide/syntax.html#Raw-HTML โ€“ codepen: https://codepen.io/anon/pen/EGOOym.

But a better approach would be create separate components for each tab.

0๐Ÿ‘

You can use is (Vue :is) for your v-for + components for each tab:

<div v-for="item in items"><component :is="item.componentName"></component></div>

Your item can be something like:

{componentName: 'Intermidiate', tasks: 100}

And in a Vue instance you should also add component like:

new Vuew({
   components: {
       Inetrmidiate,
   }
})

And the last point โ€“ just create new Vue-component named Intermidiate.

0๐Ÿ‘

The answer is here https://v2.vuejs.org/v2/guide/components.html#Dynamic-Components.
This example https://jsfiddle.net/chrisvfritz/o3nycadu/ showed exactly what I wanted.

<script src="https://unpkg.com/vue"></script>

<div id="dynamic-component-demo" class="demo">
  <button
    v-for="tab in tabs"
    v-bind:key="tab"
    v-bind:class="['tab-button', { active: currentTab === tab }]"
    v-on:click="currentTab = tab"
  >{{ tab }}</button>

  <component
    v-bind:is="currentTabComponent"
    class="tab"
  ></component>
</div>

Vue.component('tab-home', { 
    template: '<div>Home component</div>' 
})
Vue.component('tab-posts', { 
    template: '<div>Posts component</div>' 
})
Vue.component('tab-archive', { 
    template: '<div>Archive component</div>' 
})

new Vue({
  el: '#dynamic-component-demo',
  data: {
    currentTab: 'Home',
    tabs: ['Home', 'Posts', 'Archive']
  },
  computed: {
    currentTabComponent: function () {
      return 'tab-' + this.currentTab.toLowerCase()
    }
  }
})

.tab-button {
  padding: 6px 10px;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
  border: 1px solid #ccc;
  cursor: pointer;
  background: #f0f0f0;
  margin-bottom: -1px;
  margin-right: -1px;
}
.tab-button:hover {
  background: #e0e0e0;
}
.tab-button.active {
  background: #e0e0e0;
}
.tab {
  border: 1px solid #ccc;
  padding: 10px;
}

Leave a comment