1
votes

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;
      }
    });
}
}
1
Do you mean xxzz, or is there an xxyy item defined somewhere else? - Roy J
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

1 Answers

3
votes

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.