【问题标题】:VueJs - Deleting dynamically created child component always deletes the last oneVueJs - 删除动态创建的子组件总是删除最后一个
【发布时间】:2019-03-24 19:30:56
【问题描述】:

我有一个父组件customer,它有一个子组件contact 客户现在可以添加尽可能多的组件问题是,每当我从联系人列表中删除任何联系人时,它总是会删除最后一个联系人。我正在传递我需要删除的联系人并从联系人数组中正确删除但是组件没有正确删除...请参阅代码以获取详细信息...添加一些联系人,当您删除任何联系人时,最后一个联系人将被删除。 这里有什么问题或我错过了什么? here 是我的代码。 我发现了非常相似的问题here 并尝试做同样的事情,但它对我不起作用。

【问题讨论】:

    标签: vue.js vue-component


    【解决方案1】:

    对于任何有同样问题的人,经过 3 天的研究,我是如何解决这个问题的……问题是唯一的密钥应该与 for 循环一起使用,vue 将其用作更新 DOM 中正确数据的参考,所以我创建了另一个数组,每当创建新组件时,都会生成该组件的 id 并将其存储在其中。 添加组件时:

    addComponent(component) {
        this.components[component].push({id: this.id++})
    },
    

    在for循环中:

    <template v-for="(contact, index) in components.contact">
         <create-contact :count="index" @component-dispatched="catchComponent($event, 'contact')"  
              :key="contact.id" @component-removed="removeComponent($event, 'contact', index)">
         </create-contact>
    </template>
    

    请参阅小提琴以更好地理解。

    【讨论】:

      【解决方案2】:

      您应该选择整个列表作为数组,然后选择第一个,例如: 常量列表 = document.getElementById('someID'); // 然后你可以做 list[0] // call Jquery on this element to remove it

      【讨论】:

        猜你喜欢
        • 2018-01-21
        • 2020-07-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-10
        • 2020-07-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多