15

“测试”是我的 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/

4

3 回答 3

31

这是由于数组更改警告

改为这样做

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

这是小提琴

于 2017-06-28T11:19:59.303 回答
4

https://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

为我工作

于 2020-08-25T20:45:27.070 回答
2

而不是更新数组中的项目,试试这个

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

这将更新 DOM。

于 2018-10-25T11:01:19.503 回答