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.

Syntax:

<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'.

Syntax:

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

Full example:

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

Discussion (0)