对象在数据更改后不更新

对象在数据更改后不更新

本文介绍了Vue v-for 对象在数据更改后不更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 vue 版本 2.5.x

示例如下.

无论我多么努力地点击添加项目"按钮,页面中都没有显示项目.

但是添加项目版本 2"有效!

添加 :key 无济于事.有什么问题?

let app = new Vue({el: "#app",数据: {项目: {},计数:0,},方法: {添加() {this.items[this.count.toString()] = this.count;this.count++;控制台日志(this.items);},添加2(){让项目 = {}项目[this.count.toString()] = this.count;this.items = 物品;this.count++;控制台日志(this.items);}}})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script><div id="应用程序"><button @click="add">添加项目</button><button @click="add2">添加项目版本 2</button><p v-for="(item, key) in items" :keys="item">{{item}}</p>

解决方案

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

使用 Vue.set(this.items,this.count.toString(),this.count);

let app = new Vue({el: "#app",数据: {项目: {},计数:0,},方法: {添加() {Vue.set(this.items,this.count.toString(),this.count);this.count++;控制台日志(this.items);},添加2(){让项目 = {}项目[this.count.toString()] = this.count;this.items = 物品;this.count++;控制台日志(this.items);}}})

https://jsfiddle.net/zbb57ozv/

这是 javascript 或 Vue js 警告的限制.查看vue 文档变更检测警告部分了解更多信息:Vue-Js 反应性深入

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>

解决方案

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

这篇关于Vue v-for 对象在数据更改后不更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 23:02