Search code examples
javascriptvue.jsvuejs2vue-componentvue-cli

Vue create component in same component


I have a quick question that I can't find an answer for. I have a problem.

I have a component SelectForm.vue (it is a form with buttons), and now I want on button click in this SelectForm.vue component, to make another SelectForm below it. Is it possible?


Solution

  • Create a wrapper component that shows all SelectForm components. When the button is clicked on the first form, emit an event, listen for it in the wrapper, and create a new one there.

    Vue.component('Wrapper', {
        template: `<div>
            <SelectForm v-for="(form, index) in numForms" @new="numForms++" />
        </div>`,
        data() {
            return {
                numForms: 1
            }
        }
    })
    
    Vue.component('SelectForm', {
        template: `<div>
            The Form<br />
            <button @click="$emit('new')">Duplicate</button>
        </div>`
    });
    
    new Vue({
        el: "#app"
    })
    

    Here is a fiddle