Neo Ko
Neo Ko

Reputation: 1405

Vue v-for object does not update after data changed

I use vue version 2.5.x

Example like below.

No matter how hard I click "add item" the button, no item show in page.

But the "add item version 2" works!

Add :key won't help. What is the problem?

let app = new Vue({
  el: "#app",
  data: {
    items: {},
    count: 0,
  },
  methods: {
    add() {
      this.items[this.count.toString()] = this.count;
      this.count++;
      console.log(this.items);
    },
    add2() {
      let items = {}
      items[this.count.toString()] = this.count;
      this.items = items;
      this.count++;
      console.log(this.items);
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
<div id="app">
  <button @click="add">add item</button>
  <button @click="add2">add item version 2</button>
  <p v-for="(item, key) in items" :keys="item">{{item}}</p>
</div>

Upvotes: 1

Views: 7112

Answers (1)

PhmNgocNghia
PhmNgocNghia

Reputation: 141

Replace : this.items[this.count.toString()] = this.count;

with Vue.set(this.items,this.count.toString(),this.count);

let app = new Vue({
  el: "#app",
  data: {
    items: {},
    count: 0,
  },
  methods: {
    add() {
        Vue.set(this.items,this.count.toString(),this.count);

      this.count++;
      console.log(this.items);
    },
    add2() {
      let items = {}
      items[this.count.toString()] = this.count;
      this.items = items;
      this.count++;
      console.log(this.items);
    }
  }
})

https://jsfiddle.net/zbb57ozv/

It's a limitations of javascript or Vue js caveat . check out section Change Detection Caveats of vue document for more information : Vue-Js Reactivity In Depth

Upvotes: 2

Related Questions