vue.js - 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 无法检测到对数组的更改:
this.cats[this.currentCatIndex] = value;
请改用以下方法之一:
this.$set(this.cats, this.currentCatIndex, value)
// or
this.cats.splice(this.currentCatIndex, 1, value)
请参阅列表渲染注意事项。
推荐阅读
- python - 当我尝试为线性回归运行此代码时,输入包含 NaN、无穷大或对于 dtype('float64') 错误而言太大的值
- amazon-web-services - AWS - 如何使用 Javascript SDK 获取 Cloudfront 指标
- javascript - 终端输出:manpath:无法设置语言环境;确保 $LC_* 和 $LANG 是正确的
- sql - DBATools - 从 Export-DBAScript -PATH 中删除时间戳
- java - 在 Java 中创建算法
- apache-kafka - Kafka - 服务器上的内存限制
- html - 滚动在我的 HTML/CSS 网站上不起作用
- javascript - 使用 PReact(或其他框架)的苗条行为
- python - 是否有一种精确的方法来测量 Python(3.7)中特定字体的文本大小?
- templates - Twig:如果给出翻译,如何只显示内容?