【问题标题】:deleting component from array, vuejs removes wrong component从数组中删除组件,vuejs 删除错误的组件
【发布时间】: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)
    },

【问题讨论】:

    标签: vue.js vuejs2


    【解决方案1】:

    您没有 :key 绑定来告诉 Vue 哪一行与哪个组件对应。 Vue 使用快捷方式使视图看起来与视图模型的状态相同。如果您将:key="row" 添加到v-for,它会起作用。

    Updated fiddle

    【讨论】:

    • 嗨,当我删除一行并且该行之后创建了其他行然后所有这些行都被破坏并重新创建时,我遇到了一个问题,这是它的视频:@987654322 @ 你可以在这里测试它:jsfiddle.net/xk5yL3h8 不知道为什么会这样,我已经将删除按钮从子组件移到父组件上,并将 v-for 移动到包含行组件的 div 中。如何通过删除第一个行组件来避免所有其他行组件在它被破坏然后重新创建之后?
    猜你喜欢
    • 1970-01-01
    • 2021-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-06
    • 2021-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多