[Vuejs]-Vue two-way data binding issue

2👍

Data must be cloned:

new Vue({
  template: '<div>List1:<ul><li v-for="i in array1" :key="i.id">{{i.name}}</li></ul>List2:<ul><li v-for="i in array2" :key="i.id">{{i.name}}</li></ul><button @click="add">Add</button></div>',
  data: {
    array1: [{id:1, name:'Item1'},{id:2, name:'Item2'}],
    array2: []
  },
  created() {
    // clone array
    this.array2 = this.array1.map(i => Object.assign({},i))
  },
  methods: {
    add() {
      this.array1.push({id:this.array1.length+1, name:'Item'+(this.array1.length+1)})
      this.array1[0].name = 'Item1/' + this.array1.length
    }
  }
}).$mount('div')
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div></div>

If it is more complex array of objects, then must use some sort of deep-clone.

👤Darius

1👍

I solved a similar issue using the JSON parse to make the to-be-copied-array loose dinamic relation with the array-to-be-created. Try the following:

data() {
   return {
       myArray: [],
       array: []
   }
},
methods: {
   addElement() {
      myArray.push({id:1, name:'something'});
   },
   getData() {
      axios(...)
      .then(res => {
         this.array = response.data;
      });
   }
   setData() {
      this.myArray = JSON.parse(JSON.stringify(this.array)); // Here goes the trick
   }
}

This way every change on v-model array by the user won’t be reflected on myArray since the setData() is called at least once before the user interaton.

Hope it suits you well.

Leave a comment