Parent-child communication in VueJS
Child component (a row) sends event to parent component to delete itself, via $emit
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
<body>
<div id="app"></div>
</body>
JavaScript
Vue.component('row-component', {
props: ["rowData", "uniqueId"],
mounted: function() {
console.log('mounting: ' + this.uniqueId)
},
beforeDestroy: function() {
console.log('removing: ' + this.uniqueId)
},
template: `
<div>
row component: {{rowData}}
<button @click="$emit('delete-row')">Delete</button>
</div>`
})
new Vue({
el: '#app',
template: `
<div>
<row-component v-for="(row, index) in rows" :row-data="row" :uniqueId="index" v-on:delete-row="deleteThisRow(index)"></row-component>
<button @click="add()">add</button>
</div>
`,
data: {
rows: ["line1", "line2", "line3", "line4", "line5"],
},
methods: {
add() {
this.rows.push('line'+(this.rows.length+1))
},
deleteThisRow: function(index) {
this.rows.splice(index, 1)
console.log(this.rows)
}
}
})