DEV Community

Cover image for Vuejs dynamic components
Faisal Shaikh
Faisal Shaikh

Posted on • Updated on

Vuejs dynamic components

Vue dynamic components enable users to switch between two or more components and even retain the state of data when switching back to the initial component.

Some use cases are as follows:

  • Show or hide nested components based on the application state.
  • Tabbed interface like bootstrap tab pill.
  • You can even achieve router functionality without using the Vue router (not recommended for large projects). For eg. on click of the home link, we can load the home component dynamically.

Declaring a dynamic component:

Vue provides a special element to place dynamic components called 'component'. You can pass props too.


<component v-bind:is=”currentComponent” :prop1='foo' :prop2='bar'></component>
Enter fullscreen mode Exit fullscreen mode

Here currentComponent is the data property that returns the component name which needs to be mounted.

To maintain the state of the data object of components while switching between them we can use a special element called 'keep-alive'.


      <component v-bind:is="currentComponent" :prop1='foo' :prop2='bar'/>
Enter fullscreen mode Exit fullscreen mode

Full example:

  <div id="app">
      <component v-bind:is="currentComponent" />
    <button v-on:click="mountOne">One</button>
    <button v-on:click="mountTwo">Two</button>
import One from './components/One.vue'
import Two from './components/Two.vue'
import Three from './components/Three.vue'
export default {
  name: 'app',
  components: {
  data (){
    return {
  methods: {
        this.currentComponent = 'One';
        this.currentComponent = 'Two';
Enter fullscreen mode Exit fullscreen mode

Top comments (0)