Blog>
Snippets

Dynamic Component Rendering with 'component' Tag

Illustrate the usage of the special <component> tag to render components dynamically based on reactive data.
Vue.component('component-a', {
  template: '<div>Component A</div>'
});
Register a global component 'component-a' with static HTML content.
Vue.component('component-b', {
  template: '<div>Component B</div>'
});
Register another global component 'component-b' with static HTML content.
new Vue({
  el: '#app',
  data: {
    currentComponent: 'component-a'
  },
  methods: {
    toggleComponent: function () {
      // Toggle the current component between 'component-a' and 'component-b'
      this.currentComponent = this.currentComponent === 'component-a' ? 'component-b' : 'component-a';
    }
  }
});
Create a new Vue instance that controls the #app element. It includes a reactive data property 'currentComponent', which will determine the rendered component, and a method 'toggleComponent' to switch between components.
<div id="app">
  <button @click="toggleComponent">Toggle Component</button>
  <!-- The special <component> tag with ':is' binding to switch between components dynamically based on 'currentComponent' value -->
  <component :is="currentComponent"></component>
</div>
An HTML template for the Vue instance defining a button to switch the component and the special <component> tag using vue dynamic `:is` attribute to select which component to render.