javascript - 对象属性更改时,VueJs对象观察器数组不更新
问题描述
我的状态中有一组对象,如下所示:
data() {
return {
users: [{id: 1, name: 'bob'}, {id: 2, name: 'bill'}]
}
}
当我像这样更改数据时:
this.users[0].name = 'Mary'
我为该students
属性拥有的观察者没有运行,我该如何让它运行?
解决方案
index
当您使用直接访问更改任何项目或项目的子字段时,Vue.js 无法检测到数组的突变。
为此,您可以使用对象set
的方法Vue
:
// Vue.set
const index = 0;
const newValue = { ...this.users[index], name: 'Mary' };
Vue.set(this.users, index, newValue);
或者,您可以简单地使用splice
Vue.js 内部覆盖的方法来操作数组:
const index = 0;
const newValue = { ...this.users[index], name: 'Mary' };
// Using array manipulation
this.users.splice(index, 1, newValue);
或者,您可以将不可变数据实践用作:
const newArray = [...this.users];
const newValue = { ...this.users[0], name: 'Mary' };
newArray[0] = newValue;
this.users = newArray;
推荐阅读
- tsql - 使用T-SQL在SSMS中执行SSIS(包)并返回一个值
- powershell - HKLM 的 Get-ChildItem 为 Windows Powershell 返回的结果少于为 VS2019 的 Developer Powershell 返回的结果
- r - 为什么某些 jsonl 文件无法在 SparklyR 中加载
- java - 异常:java.sql.SQLException:非法连接端口值 '3306:etude'
- app-inventor - MIT App Inventor 2 有没有办法刷新屏幕?
- c# - 使用 Chromium 在 WPF 中自动播放 YouTube 视频
- android - 如何在 Android Studio 中设置数据绑定?
- c++ - 为什么 switch 构造中的声明是合法的?
- python - 使用条件识别行后的 Xlsxwriter 条件格式
- excel - 用VBA写这个公式