Home > Enterprise >  Vue 3: Each button click, generate new component and append as child in the target element
Vue 3: Each button click, generate new component and append as child in the target element

Time:12-25

I have been searching for a simple solution to generate components in a Vue 3 app programmatically. So far, I've used defineComponent to extend the div component and attach it to the main component via createApp and mount:

Main Component

<template>
 <button type="button" v-on:click="addDiv"></button>
 <div id="app-main">
 </div>
</template>

<script>
 import {defineComponent, createApp} from 'vue'
 import Div from './components/Div.vue'

 export default{
  name: 'App',
  methods: {
   addDiv: () => {
    let newDiv = defineComponent({extends: Div});
    createApp(newDiv).mount("#app-main");
   }
  }
 }
</script>

Div Component:

<template>
 <div>This is a div</div>
</template>

<script>
 export default {
  name: 'Div'
 }
</script>

My issue with this is that mount replaces everything in the target element. If you click the button 3 times, only 1 div appears instead of 3. I need a method where the code appends the component as a child in the target element allowing me to create as many div components as I want. Thanks in advance!

CodePudding user response:

Don't use mount as that is designed to mount a new Vue instance. What you want to use is the <component :is="component_name"> feature and possibly have an array or other data structure containing the list of components you wish to have rendered.

For instance, consider the following simple example:

Vue.component('my-component', {
    // component config goes here, omitting for simplicity.
});

new Vue({
    el: '#app',
    data: {
        elements: []
    },
    methods: {
        addNewDiv() {
            this.elements.push({type: 'my-component'});
        }
    }
});
<div id="app">
    <component v-for="element in elements" :is="element.type"></component>
</div>

This will iterate over the elements array dynamically and will replace each instance of the <component> tag with whatever is defined by the array element.

  • Related