【问题标题】:Vue.js removing elements from list of jsons by their indexVue.js 通过索引从 json 列表中删除元素
【发布时间】:2016-10-17 10:14:16
【问题描述】:

我正在尝试创建一个元素列表,每个元素都有“删除”按钮,该按钮应该删除它所引用的特定元素。

如此处所示: http://jsbin.com/jalexekeho/edit?html,js,console,output

我在使用时遇到的问题

<person v-for="(person,index) in list"\
    :settings="person"\
    @remove="list.splice(index, 1)">\
    </person>

视图不显示“设置”(姓名、姓氏)

如果我正在使用

<person v-for="person in list"\
        :settings="person"\
        @remove="list.splice(index, 1)">\
        </person>

所有设置都将按预期显示,但是(!)删除按钮将导致第一个元素被删除。 (索引始终为 0)

如何在不为每个元素使用预定义键的情况下以优雅的方式解决这个问题?

JS 脚本是

Vue.component('person', {
  template: '<div>{{ settings.name }}\
     {{ settings.last}}</div>\
     <button @click="$emit(\'remove\')" >remove</button>',
  props:['settings']
})


Vue.component('people', {
  template: '<person v-for="(person,index) in list"\
    :settings="person"\
    @remove="list.splice(index, 1)">\
    </person> \
  ',
  props: ['list'],  
});


new Vue({
  el: '#app',
})

【问题讨论】:

  • 您似乎使用的是旧版本的 Vue。在Ver 1.xv-for有隐式变量$index,不能显式声明。

标签: vue.js


【解决方案1】:

这是关于 VueJS 版本的 - 好像你遵循了 Vue 2.0 的文档 - 在 JsBin 上你使用的是 1.0。

在 VueJS 2.0 中,$index 已被弃用。

这应该可以工作

Vue.component('person', {
  template: '<div>{{ settings.name }}\
     {{ settings.last}}</div>\
     <button @click="$emit(\'remove\')" >remove</button>',
  props:['settings']
})


Vue.component('people', {
  template: '<person v-for="person in list"\
    :settings="person"\
    @remove="list.splice($index, 1)">\
    </person> \
  ',
  props: ['list'],  
});


new Vue({
  el: '#app',
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-24
    • 1970-01-01
    • 1970-01-01
    • 2012-08-03
    • 1970-01-01
    • 2010-10-12
    相关资源
    最近更新 更多