当我删除组件后删除并重新创建后创建的任何组件时,我遇到了问题。有问题的组件被删除,子组件在被删除后重新创建。
为什么会发生这种情况?
小提琴代码:
Vue.component('column-component', {
props: ["columnData", "uniqueId"],
mounted: function() {
console.log('mounting column: ' + this.uniqueId)
},
beforeDestroy: function() {
console.log('removing: ' + this.uniqueId)
},
template: `
<div style="float: left; padding: 10px; margin-right: 10px; border: 1px solid black;">aaa</div>`
})
Vue.component('row-component', {
props: ["rowData", "uniqueId"],
data: function data() {
return {
columns: [],
columnCount: 0
}
},
mounted: function() {
console.log('mounting row: ' + this.uniqueId)
},
methods: {
addColumn() {
console.log
var column = new Object()
column.uniqueId = this.uniqueId +'.col.'+ this.columnCount
this.columns.push(column)
this.columnCount = this.columnCount + 1
}
},
beforeDestroy: function() {
console.log('removing: ' + this.uniqueId)
},
template: `
<div>
<div style="margin: 10px; padding: 20px; background: rgba(0,0,0, 0.5);">
row component: {{rowData.text}}
<div class="column" v-for="(column, index) in columns">
<column-component column-data="abc" :uniqueId="column.uniqueId"></column-component>
</div>
<div style="clear: both;"></div>
<div style="margin-top: 35px;">
<button @click="addColumn()">add column</button>
</div>
</div>
</div>`
})
new Vue({
el: '#app',
template: `
<div>
<div v-for="(row, index) in rows">
<row-component :uniqueId="row.uniqueId" :row-data="row" :key="row.uniqueId"></row-component>
<button @click="deleteThisRow(index)">remove row</button>
</div>
<button @click="addRow()">add</button>
</div>
`,
data: {
rows: [],
rowCount: 0
},
mounted: function() {
this.addRow()
this.addRow()
this.addRow()
},
methods: {
addRow() {
var row = new Object()
row.uniqueId = 'row-' + this.rowCount
row.text = 'row-'+(this.rows.length)
this.rows.push(row)
this.rowCount = this.rowCount + 1
},
deleteThisRow: function(index) {
this.rows.splice(index, 1)
console.log(this.rows)
}
}
})
答案 0 :(得分:2)
完全更新
好的,我今天学到了一些东西:
:key
goes on the v-for
element。很多时候,v-for
都在组件本身上,因此将key
放在组件或v-for
元素上没有区别。你有div
v-for
包裹组件,它会有所不同。它应该是:
<div class="column" v-for="(column, index) in columns" :key="column.uniqueId">
<column-component column-data="abc" :uniqueId="column.uniqueId"></column-component>
</div>
和
<div v-for="(row, index) in rows" :key="row.uniqueId">
<row-component :uniqueId="row.uniqueId" :row-data="row"></row-component>
<button @click="deleteThisRow(index)">remove row</button>
</div>