Categories
Vue Answers

How to dynamically add different components in Vue.js?

Spread the love

Sometimes, we want to dynamically add different components in Vue.js.

In this article, we’ll look at how to dynamically add different components in Vue.js.

How to dynamically add different components in Vue.js?

To dynamically add different components in Vue.js, we can use the component component.

For instance, we write

<template>
  <div>
    <component
      v-for="field in fields"
      :is="field.type"
      :key="field.id"
    ></component>
  </div>
</template>

<script>
export default {
  //...
  data() {
    return {
      fields: [
        { id: 1, type: "Foo" },
        { id: 2, type: "Bar" },
        { id: 3, type: "Baz" },
      ],
    };
  },
  //...
};
</script>

to add the fields array that has the id and type properties in each fields entry.

The type property of each object is set to the name of the component we want to render.

We use v-for to loop through each fields entry and nd we render all the components with the component component with the is prop set to the component name string.

Conclusion

To dynamically add different components in Vue.js, we can use the component component.

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 *