How to create a  dynamic Component with Vue Composition API

How to create a dynamic Component with Vue Composition API

·

1 min read

This tutorial assumes you already have some experience with vue. I was working on a project using the vue composition API and I had to build a tab that outputs different components based on a click of a button I know this is achievable with the v-if directives but imagine a scenario where we have many components to render that will be lots of if-statement. I remembered I could do dynamic components using option API.

NB: was using composition API for the first time

Tried googling and all I saw was the options API way. Finally figured it out and this is how it's done

<template>
 <h1>Dynamic Component</h1>
 <section>
   <button @click="tab=TabA">TabA</button>
   <button @click="tab=TabB">TabB</button>
   <button @click="tab=TabC">TabC</button>
 </section>
 <component :is="tab"/>
</template>

<script setup>
import {shallowRef} from 'vue';
 import TabA from './components/TabA';
 import TabB from './components/TabB';
 import TabC from './components/TabC';
const tab= shallowRef(null)
</script>

<style lang='scss'>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

I used shallow ref just for performance issues ref would work too you could read up on shallow ref from the Vue docs

here is the codesand box to see it in action

Happy coding ✌...