I'm new to Vue and have been trying to figure this out for days without finding a solution that works...
How do I add an external vue-component multiple times @click on button?
Hopefully my pseudo-code below will explain what i'm trying to do.
<template>
<div>
<Piece/>
<!-- HERE I WANT TO ADD MULTIPLE "<Piece/>" @click on below button -->
<button type="button" @click="addPiece">Add Piece</button>
</div>
</template>
<script>
import Piece from "@/components/Piece.vue";
export default {
name: "PiecesModal",
components: {
Piece,
},
methods: {
addPiece () {
this.components.push(Piece)
}
},
};
</script>
Vue is "data driven"
Instead of wasting time "figuring this out for days", just read the excellent docs, List Rendering in this case...
const piece = Vue.component('Piece', {
props: ['number'],
template: `<div> Piece {{ number }} </div>`
})
const app = new Vue({
el: "#app",
components: { piece },
data() {
return {
counter: 0,
pieces: []
}
},
methods: {
addPiece() {
this.pieces.push(this.counter)
this.counter++
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<button type="button" @click="addPiece">Add Piece</button>
<hr>
<Piece v-for="piece in pieces" :key="piece" :number="piece"/>
</div>