Categories
JavaScript Vue

Displaying Dynamic Components in Vuejs

Spread the love

We can display Vuejs components dynamically.

The is prop can be used to display components dynamically.

It just takes a string of the component name.

For instance, we can create components and display them dynamically as follows:

Archives.vue

<template>
  <div id="app">archives</div>
</template>

<script>
export default {
  name: "Archives"
};
</script>

Home.vue

<template>
  <div id="app">home</div>
</template>

<script>
export default {
  name: "Home"
};
</script>

Posts.vue

<template>
  <div id="app">posts</div>
</template>

<script>
export default {
  name: "Posts"
};
</script>

App.vue

<template>
  <div id="app">
    <button @click="currentTab = 'Home'">home</button>
    <button @click="currentTab = 'Posts'">posts</button>
    <button @click="currentTab = 'Archives'">archive</button>
    <component :is="currentTab"></component>
  </div>
</template>

<script>
import Home from "./components/Home";
import Posts from "./components/Posts";
import Archives from "./components/Archives";

export default {
  name: "App",
  components: {
    Home,
    Posts,
    Archives
  },
  data() {
    return {
      currentTab: "home"
    };
  }
};
</script>

We’ve to register the components in App.vue.

Also, we have buttons in the template to change the value of currentTab to the string of the component name.

Then we add the component component with the is prop which is set the name string of the component so that a component can be displayed dynamically.

Now when we click on each button, we see the content of each component displayed.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *