Being able to render components dynamically is one of the coolest features in Vue.js. What it means is that we can display a component only when we’re able to match the component name by a condition.
Consider we have two components named ComponentA and ComponentB. We’ll display only one of these components at a time. We’d create a button which switch between these components to be rendered at the same exact place.
Let’s create a component ComponentA.vue as follows:
<template>
<div>
<h2>Component A</h2>
</div>
</template>
Code language: HTML, XML (xml)
Let’s create another component named ComponentB.vue as below:
<template>
<div>
<h2>Component B</h2>
</div>
</template>
Code language: HTML, XML (xml)
Now, let’s import these two components in another component Main.vue:
<script setup>
import ComponentA from "./ComponentA.vue";
import ComponentB from "./ComponentB.vue";
import { ref } from "vue";
const currentComponentName = ref("ComponentA");
const components = {
ComponentA,
ComponentB,
};
const toggleCurrentComponent = () => {
currentComponentName.value =
currentComponentName.value == "ComponentA" ? "ComponentB" : "ComponentA";
};
</script>
<template>
<div>
<component :is="components[currentComponentName]"></component>
<button @click="toggleCurrentComponent">Toggle</button>
</div>
</template>
Code language: HTML, XML (xml)
In the above code, we’ve imported two components named ComponentA and ComponentB. We’ve initialized a reactive state by the name currentComponentName with default value ‘ComponentA‘
We then create a components object referring to the imported components.
In the template, we use the :is directive to dynamically set the component by the component name.
We also created a method named toggleCurrentComponent to change the component names. We call this method from the button in the template.
This is how the above example would look in action:
You can find a working copy of the above example from my repo links below: