Yuval Kaufman
Yuval Kaufman

Reputation: 677

Vue.js removing elements from list of jsons by their index

I'm trying to create a list of elements that each element has "remove" button that should remove the specific element that it refers to.

As presented here: http://jsbin.com/jalexekeho/edit?html,js,console,output

my problem that whenever I'm using

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

the view doesn't show the "settings" (name, last)

If I'm using

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

the all the settings will be displayed as expected but(!) the remove button will cause the first element to be removed. (index is always 0)

How can I solve this problem in an elegant way without using a pre defined key for each element ?

the JS script is

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',
})

Upvotes: 0

Views: 338

Answers (1)

Belmin Bedak
Belmin Bedak

Reputation: 9201

It's about VueJS version - seems like you followed the docs from Vue 2.0 - on JsBin you are using the 1.0.

In VueJS 2.0 $index is deprecated.

This should work

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',
})

Upvotes: 1

Related Questions