首页 > 解决方案 > 对象属性更改时,VueJs对象观察器数组不更新

问题描述

我的状态中有一组对象,如下所示:

data() {
    return {
    users: [{id: 1, name: 'bob'}, {id: 2, name: 'bill'}]
    }
}

当我像这样更改数据时:

this.users[0].name = 'Mary'

我为该students属性拥有的观察者没有运行,我该如何让它运行?

标签: javascriptvue.js

解决方案


index当您使用直接访问更改任何项目或项目的子字段时,Vue.js 无法检测到数组的突变。

为此,您可以使用对象set的方法Vue

// Vue.set
const index = 0;
const newValue = { ...this.users[index], name: 'Mary' };

Vue.set(this.users, index, newValue);

或者,您可以简单地使用spliceVue.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;

推荐阅读