Vue Dynamic Components

Apr 22, 2020

Vue's component component can dynamically render a different component based on the state of your data. The is attribute is how you can tell component what component to render. For example, below is a simple tab UI:

The above tabbed UI consists of 3 different Vue components: home, about, and contact.

Vue.component('home', {
  template: '<div>This is the home tab</div>'
});
Vue.component('about', {
  template: '<div>This tab talks about us</div>'
});
Vue.component('contact', {
  template: '<div>This tab provides contact info</div>'
});

Using component and :is, Vue can render different components based on the state of tab:

<component class="tab-content" :is="tab"></component>

Whenever tab changes, Vue changes what component is rendered. Below is the full Vue app that handles the state of tab.

const app = new Vue({
  data: () => ({ tab: 'home' }),
  methods: {
    selected: function(tab) {
      return tab === this.tab ? 'selected' : '';
    }
  },
  template: `
    <div>
      <div class="buttons">
        <button @click="tab = 'home'" :class="selected('home')">
          Home
        </button>
        <button @click="tab = 'about'" :class="selected('about')">
          About Us
        </button>
        <button @click="tab = 'contact'" :class="selected('contact')">
          Contact Us
        </button>
      </div>
      <component class="tab-content" :is="tab"></component>
    </div>
  `
});
app.$mount('#vue-tab-example');

Vue School has some of our favorite Vue video courses. Their Vue.js Master Class walks you through building a real world application, and does a great job of teaching you how to integrate Vue with Firebase. Check it out!


Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Vue Tutorials