-1

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>
Chris
  • 6,093
  • 11
  • 42
  • 55

2 Answers2

1

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

mava
  • 2,544
  • 1
  • 10
  • 17
0

You should make a copy of this with this.items.slice(0)

new Vue({
  el: "#app",
  data: {
    items: ['foo', 'bar']
  },
  computed: {
    someComputed() {
      let some = this.items.slice(0)
      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>
Maxim
  • 2,233
  • 6
  • 16