Search code examples
vue.jscomputed-properties

Why does computed change data when assigning data to a variable?


I just realized a strange behavior of Vue.js when using computed properties. Maybe I am missing something and this is the right behavior but for me it doesn’t make sense. If you have a look at the following code you will see inside the computed property I created a new variable and assigned an array defined in “data”. I then pushed some new data into the newly created variable. Now the array in “data” has also changed! Why is that?

new Vue({
  el: "#app",
  data: {
    items: ['foo', 'bar']
  },
  computed: {
    someComputed() {
      let some = this.items
      some.push('foobar')
      return some
    }
  }
})
<div id="app">
  {{ someComputed }} – {{ items }}
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>


Solution

  • This is because "Call by Reference", you are just referencing the array from data. It's like a pointer, some and this.items are pointing to the same object.
    If you want a copy of this.items you need to call.

    let some = this.items.slice()
    

    This way you are getting a whole new object and not just a new "reference".
    Normaly JS is "Call by Value" but for objects and arrays, the value is the reference.
    Edit:
    Have a look at: Javascript passing arrays to functions by value, leaving original array unaltered