学习优先度:★★★★☆
难易度:★★★☆☆
在对象上添加或删除属性时,Vue 的反应性系统不会自动检测。
在 Vue 中,当您添加或删除对象上的属性时,Vue 的反应性系统不会自动检测到这些变化。相反,您需要使用 Vue.set 或 Vue.delete 进行此类操作,以确保反应性。
【代码示例】
// Creating a reactive object in Vue
const vm = new Vue({
data: {
user: {
name: 'John Doe',
age: 30
}
}
});
// Adding a new property without Vue.set
vm.user.email = 'john.doe@example.com';
// Vue will not react to changes on 'email'
console.log(vm.user.email); // Output: john.doe@example.com (but Vue reactivity doesn't track this change)
// Correct way to add a new property to an object
Vue.set(vm.user, 'email', 'john.doe@example.com');
// Vue will now react to changes on 'email'
console.log(vm.user.email); // Output: john.doe@example.com (Vue reactivity tracks this change)
【执行结果】
// Output: john.doe@example.com (but Vue reactivity doesn't track this change)
// Output: john.doe@example.com (Vue reactivity tracks this change)
Vue 的反应性系统旨在检测现有属性的变化,但无法自动检测属性的添加或删除。这是由于 Vue 用来实现反应性的 JavaScript Object.defineProperty 方法存在限制。为了解决这个问题,Vue 提供了 Vue.set 和 Vue.delete 等方法来添加或删除属性,同时保持反应性。
【补充】
在添加或删除属性时,使用 Vue.set 或 Vue.delete 可确保 Vue 反应系统了解这些更改。这在处理深嵌套对象或在运行期间有条件地添加属性时尤其有用。