首页 > 解决方案 > Vue.js 应用程序未按预期更新视图

问题描述

我已将这个小应用程序中的输入绑定到一个名为的计算属性currentCat,该属性同时具有 getter 和 setter 方法。使用console.log它可以看到该cats数组已被属性更新,但没有任何更改反映在呈现的 html 中。

这是应用程序的 HTML:

<div id="app">
  <ul>
    <li v-for="cat in cats">{{ cat }}</li>
  </ul>
  <div>{{ currentCat }}</div>
  <input type="text" v-model="currentCat">
</div>

这是JavaScript:

let app = new Vue({
  el: "#app",
  data: {
    currentCatIndex: 0,
    cats: ["Bob", "Tom", "Cat", "Dog"]
  },
  computed: {
    currentCat: {
      get() {
        return this.cats[this.currentCatIndex];
      },
      set(value) {
        console.log(value, this.cats[this.currentCatIndex]);
        this.cats[this.currentCatIndex] = value;
        console.log(this.cats[this.currentCatIndex]);
      }
    }
  }
});

当计算属性的setter运行时,html中的列表和div不应该自动更新吗?

标签: vue.js

解决方案


当您执行以下操作时,Vue 无法检测到对数组的更改:

this.cats[this.currentCatIndex] = value;

请改用以下方法之一:

this.$set(this.cats, this.currentCatIndex, value)

// or
this.cats.splice(this.currentCatIndex, 1, value)

请参阅列表渲染注意事项


推荐阅读