首页 文章

从数组中删除组件,vuejs删除错误的组件

提问于
浏览
2

我需要能够从数组中删除特定组件 . 我使用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)
    },

1 回答

  • 6

    你没有 :key 绑定来告诉Vue哪一行与哪个组件相关 . Vue使用快捷方式使视图看起来与viewmodel的状态相同 . 如果将 :key="row" 添加到 v-for ,它可以正常工作 .

    Updated fiddle

相关问题