19

"test" is an array of object in my vue data

var vue = new Vue({
  el: '#content',

  data: {
    test: [
      {
        array: [0, 0, 0, 0]
      },
      {
        array: [0, 0, 0, 0]
      }
    ],
    number: 0
  },

  methods: {   
    setNumber: function(){
      this.number = 5;
    },

    setArray: function(){
      this.test[0].array[0] = 9;
    }
  }
})

Problem is that if i change the value of an element in "array", while log shows that the value has changed, it doesn't update on the page. On the other hand, if i change value of "number", both "number" and "array" value on the page are updated.

<section id="content">
  <div>Value in array: {{ test[0].array[0] }}</div>
  <div>Value in number: {{ number }}</div>
  <!-- {{ setNumber() }} -->
  {{ setArray() }}
</section>

<!-- Loading Vue.js -->
<script src="https://unpkg.com/vue"></script>
<script src="https://cdn.jsdelivr.net/vue.resource/1.3.1/vue-resource.min.js"></script>

How can i make my page responsive to "array" update?
Here's the JsFiddle: https://jsfiddle.net/zcbh4esr/

Andreas
  • 21,535
  • 7
  • 47
  • 56
Razinar
  • 727
  • 3
  • 13
  • 21

3 Answers3

36

This is due to the array change caveats.

Do it like this instead

var vue = new Vue({
  el: '#content',

  data: {
    test: [{
      array: [0, 0, 0, 0]
    }, {
      array: [0, 0, 0, 0]
    }],
    number: 0
  },

  methods: {
    setNumber: function() {
      this.number = 5;
      console.log(this.number);
    },
    setArray: function() {
      //this.test[0].array[0] = 9;
      this.$set(this.test[0].array, 0, 9);
      console.log(this.test[0].array[0]);
    }
  }
});

 

Here is thefiddle

tony19
  • 125,647
  • 18
  • 229
  • 307
Vamsi Krishna
  • 30,568
  • 8
  • 70
  • 78
5

From

https://v2.vuejs.org/v2/guide/reactivity.html

var vm = new Vue({
  data: {
    items: ['a', 'b', 'c']
  }
})

//vm.items[1] = 'x' // is NOT reactive
Vue.set(vm.items, indexOfItem, newValue)  //works fine

worked for me

tony19
  • 125,647
  • 18
  • 229
  • 307
parsecer
  • 4,758
  • 13
  • 71
  • 140
2

Instead of updating items inside the array, try this

 this.users = Object.assign({},newList);

This will update the DOM.

JD-V
  • 3,336
  • 1
  • 17
  • 20