// 使用 Vue.set 添加一个属性到响应式对象中
new Vue({
el: '#app',
data: {
user: {
name: 'John Doe'
}
},
mounted() {
// 正确的方式:使用 Vue.set 添加新的响应式属性
Vue.set(this.user, 'age', 30);
// 或者使用 this.$set 方法(等价于 Vue.set)
this.$set(this.user, 'address', '1234 Elm Street');
}
});
/*
解释:
1. `Vue.set` 是 Vue 提供的一个全局方法,用于向响应式对象中添加新属性,并确保该属性也是响应式的。
2. 如果直接在已有的响应式对象上添加属性(例如 `this.user.age = 30`),Vue 无法检测到这个变化,因此不会触发视图更新。而使用 `Vue.set` 或 `this.$set` 可以避免这个问题。
*/
上一篇:vue xlsx
下一篇:vue拿不到$event
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站