FrontendDeveloper.in

Vue.js question detail

What are dynamic components?

The dynamic component will allow you to dynamically switch between multiple components without updating the route of the application and even retaining the state of the component when switching back to the initial component. It works by using <component> tag with v-bind:is attribute which accept dynamic component.

Let's create a dynamic component vue instance to switch between different pages of a website,

new Vue({
el: '#app',
data: {
currentPage: 'home'
},
components: {
home: {
template: "<p>Home</p>"
},
about: {
template: "<p>About</p>"
},
contact: {
template: "<p>Contact</p>"
}
}
})

Now you can use the dynamic component which holds the current page,

<component v-bind:is="currentPage">
<!-- component changes when currentPage changes! -->
<!-- output: Home -->
</component>

The component will be unmounted when it is switched away but it is possible to force the inactive component alive using <keep-alive> component

Note: The value of :is attribute can be either name of the registered component or the actual imported object itself.

Back to all Vue.js questions
Get LinkedIn Premium at Rs 399