【发布时间】:2018-01-24 10:29:18
【问题描述】:
我需要能够从数组中删除特定组件。我使用 splice 执行此操作,尽管从数组中删除了该组件定义,但 vuejs 删除了错误的组件。它总是删除最后添加的组件。
这是一个提供演示的小提琴:
https://jsfiddle.net/wjjonm8n/
这里有视频显示正在发生的事情:
https://maxniko.tinytake.com/sf/MTg3NTI5NF82MDIxNDAx
这里有一些代码:
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)
}
}
})
这个函数告诉我 vuejs 真正删除了什么:
beforeDestroy: function() {
console.log('removing: ' + this.uniqueId)
}
如果您查看 console.log 函数打印的内容,它会删除最后添加的组件。这是问题,因为在安装每个组件时,我只为该组件创建侦听器:
this.$bus.$on('column-'+this.uniqueId+'-add-block', this.handlerMethod)
当 vue 移除最后一个组件时,这个事件监听器不再起作用。
我该如何解决这个问题?
在我自己的应用程序中,这是我创建子组件的方式:
let column = new Object()
column.uniqueId = this._uid+'-column-' + this.addedColumnCount
column.text = '1/2'
this.columnList.push(column)
this.addedColumnCount = this.addedColumnCount + 1
请注意我在添加组件时如何为组件创建 uniqueId:
column.uniqueId = this._uid+'-column-' + this.addedColumnCount
当我尝试删除一个组件时,它总是向我报告最后添加的 uniqueId 的组件正在被删除。
beforeDestroy: function() {
this.$bus.$off('column-'+this.uniqueId+'-add-block', this.handlerMethod)
console.log('removing: ' + this.uniqueId)
},
【问题讨论】: