简体   繁体   中英

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

This behavior is causing problems in my projects. This is a simplified version of what's happening. I'd like to learn why this happens, and how I can avoid it. I have vue loaded in the head of my website:

<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.js"></script>

And this is the Vue object:

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

Now, my issue is this. How do I save a copy of the “array” data item from the Vue Object so I can manipulate it without actually modifying the real array Vue data item? This is what I'm trying to do, but it isn't working as intended;

var arrayCopy = vueObject.array;
arrayCopy.push("x");

This is causing both arrayCopy and vueObject.array to be set to [“x”]. I only want to add “x” to arrayCopy. How can I do that? Why does this happen?

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.

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> 

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);
    }
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM