Vuejs Dynamic Components Example
In this tutorial, 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 dynamically
switch 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.