[Vuejs]-Vue JS – Setting variable to vueObject.dataItem and modifying it also modifies the Vue data item

2👍

You’re referencing the vueObject.array by doing var arrayCopy = vueObject.array; not copying it to arrayCopy, so to avoid that use let arrayCopy = vueObject.array.slice(); or Object.assign(arrayCopy, vueObject.array)

let vueObject = new Vue({
  el: '#app',
  data: {
    array: ['a', 'b']
  }
});

let arrayCopy = vueObject.array.slice();
arrayCopy.push('x');

console.log(arrayCopy);
console.log( vueObject.array);
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.4/vue.min.js"></script>
<div id="app"></div>

2👍

Objects are assigned by reference. When you assign an array, you are just making another variable refer to the same object. Modifying the contents of an object will be reflected in everything that references that object.

An array copy would be arrayCopy = vueObject.array.slice(), but the same caveat applies to any Objects contained in the array: if you modify their contents, those modifications will show up in both arrays. See more answers in the linked thread about deep copying.

👤Roy J

1👍

Another option is to create a new Array and spread the vue data array inside the new array so we copy all its original values, but then manipulate it as it’s own context.

new Vue({
  el: "#app",
  data: {
    array: [1, 2, 3]
  },
  created: function() {
    this.doSomething();
  },
  methods: {
    doSomething() {
      const copy = [...this.array];
      copy.push(4);
      console.log("copy:", copy);
      console.log("origninal", this.array);
    }
  }
});
👤Win

Leave a comment