1

I am having some odd behaviour on my component. I have a list of buttons and when clicked each is supposed to be removed from the DOM by removing it from the array. In this case I am using the function removeItem and passing it the index of the item. That works fine and it is being removed from the array abc[] but what is unexpected is that the same item is being removed from another array xxzz[]

<template>
    <button v-for="(item, index) in abc" @click="removeItem(index)">{{ item.name }}</button>
</template

export default {
data: () => ({
  abc: [],
  xxzz: [],
}),
methods: {
  removeItem(index){
    this.abc.splice(index, 1);
  },
},
created(){
  var vm = this;
  let formData = new FormData();
  axios({
      url: '/get/items', 
      method: 'post',
      data: formData
    })
    .then(function (response) {
      if(response.status == 200){
        vm.abc = response.data.items;
        vm.xxzz = response.data.items;
      }
    });
}
}
Kal
  • 948
  • 17
  • 30
  • Do you mean `xxzz`, or is there an `xxyy` item defined somewhere else? – Roy J Jan 11 '18 at 21:56
  • 1
    I wonder if perhaps `abc` and `xxzz` are actually the same object because you are making them from the same source. Could you try building `xxzz` with `Object.assign( {} , response.data.items )` to see if that helps? – JakeParis Jan 11 '18 at 21:58

1 Answers1

3

You are setting both items to the same array:

    vm.abc = response.data.items;
    vm.xxzz = response.data.items;

Assignment of objects is done by reference. In this case, abc and xxzz both refer to the same underlying array. When you modify it in one, you modify it in the other. You probably want to make a copy.

Roy J
  • 42,522
  • 10
  • 78
  • 102