微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

vue.js – 从数组中删除组件,vuejs删除错误的组件

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

解决方法

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

Updated fiddle

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐