Skip to content

Posts › Development

Development

Load dynamic Vue components based on a prop string

Learn how to use a dynamic component by passing its name through a string prop.

2 min read
Load dynamic Vue components based on a prop string

Introduction

In the case you need to load a Vue component dinamically by passing its name as a property you can do it as follows:

Create folder structure

Create a folder with all the required components and an index.js file

text
 1app/
 2├── DynamicComponent.vue
 3├── components/
 4│   ├── index.js
 5│   ├── Component1.vue
 6│   ├── Component2.vue
 7│   └── Component3.vue
 8...

The index.js file should contain the following:

javascript
 1export { default as Component1 } from './Component1'
 2export { default as Component2 } from './Component2'
 3export { default as Component3 } from './Component3'

Define the dynamic component

Create DynamicComponent as follows:

vue
 1<template>
 2  <component :is="type"></component>
 3</template>
 4
 5<script>
 6  import * as components from './components/index'
 7
 8  export default {
 9
10    components: {
11      ...components
12    },
13
14    props: {
15      type: { type: String, required: true }
16    },
17  }
18</script>

Use your dynamic component

Use it your components like this:

xml
 1<dynamic-component type="Component1"></dynamic-component>
 2
 3<dynamic-component type="Component2"></dynamic-component>
 4
 5<dynamic-component type="Component3"></dynamic-component>