Vuejs dynamic components

faisalshaikh8433

Faisal Shaikh

Posted on March 13, 2021

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
💖 💪 🙅 🚩
faisalshaikh8433
Faisal Shaikh

Posted on March 13, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

A single page with vue
vue A single page with vue

May 1, 2021

Vuejs dynamic components
vue Vuejs dynamic components

March 13, 2021