Vue.js - 更新数组项的值不会在页面上更新

19

"test" 是我的 Vue 数据中的一个对象数组

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;
    }
  }
})

问题在于,如果我改变了“数组”中一个元素的值,控制台显示该值已更改,但页面上并未更新。另一方面,如果我改变“数字”的值,页面上的“数字”和“数组”值都会更新。

<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>

如何使我的页面对"数组"更新响应?
这里是JsFiddle:https://jsfiddle.net/zcbh4esr/

3个回答

36

这是由于数组改变警告导致的。

请改用以下方式进行操作

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]);
    }
  }
});

 

这里是代码片段


@JuveLover 很高兴能帮忙 :) - Vamsi Krishna

5

2

尝试使用以下方法而不是更新数组中的项:

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

这将更新文档对象模型(DOM)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接