Vuejs Dynamic Components Example
In this post we will give you information about Vuejs Dynamic Components Example. Hear we will give you detail about Vuejs Dynamic Components ExampleAnd how to use it also give you demo for it if it is necessary.
we are going to learn about how to dynamically switch from one component to another component in vuejs.
This tutorial assumes that you already created a new Vue app using vue-cli.
Let’s create two new components in our App.
<template><div> <h1>Hello user1</h1></div></template><script></script>
<template><div> <h1>Hello user2</h1></div></template><script></script>
Now import this two components inside App.vue file and register it.
<template><div id="app"> <h1>App component</h1></div><template><script> import User1 from './user1.vue'; import User2 from './user2.vue';export default { components:{ 'app-user1':User1, 'app-user2':User2 }}</script>component element
Vuejs provides us a <component> element with :is special attribute by using that we can dynamicallyswitch between components.
Now update your App.vue file with the below code.
<template><div id="app"> <h1>App component</h1> <component :is="selectedComponent"></component> <button @click="selectedComponent='app-user1'">Switch to user1</button> <button @click="selectedComponent='app-user2'">Switch to user2</button></div><template><script> import User1 from './user1.vue'; import User2 from './user2.vue';export default { data: function(){ return { //initially we selected 'user1' component selectedComponent: "app-user1" } } components:{ 'app-user1':User1, 'app-user2':User2 }}</script>In the above code, we added a <component> element with :is attribute binding to selectedComponent property.
selectedComponent property holds the value of a registered component name (app-user1).
When we click on a Switch to user1 button we are dynamically switching to User1 component similarly when we click on a Switch to user2 button we are switching to User2 component.
keep-alive element
When switching between dynamic components every time vue creates a new Vue instance, so that if any state contains in our component is re-initialized and we lost the old data.
To stay in the old state we need to wrap our component element with the keep-alive.
<keep-alive> <component :is="selectedComponent"></component></keep-alive>
Now our state is cached by the vue.
Hope this code and post will helped you for implement Vuejs Dynamic Components Example. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs
