// 示例代码:使用 Vue 的 this.$set 方法
new Vue({
el: '#app',
data: {
message: 'Hello Vue!',
obj: {
name: 'Vue'
}
},
methods: {
updateMessage() {
// 直接修改 message,Vue 可以检测到变化并更新视图
this.message = 'Hello World!';
},
addObjectProperty() {
// 使用 this.$set 添加新属性,确保 Vue 检测到变化并更新视图
this.$set(this.obj, 'age', 3);
}
}
});
// HTML 部分
<div id="app">
<p>{{ message }}</p>
<p>{{ obj.name }} - {{ obj.age }}</p>
<button @click="updateMessage">Update Message</button>
<button @click="addObjectProperty">Add Object Property</button>
</div>
// 解释说明:
// 1. `this.$set` 是 Vue 提供的一个方法,用于向响应式对象中添加新的属性,并确保这个属性也是响应式的。
// 2. 如果直接在已有的响应式对象上添加新属性(例如 this.obj.newProp = value),Vue 无法检测到这个变化,因此不会更新视图。
// 3. 使用 `this.$set(target, propertyName/index, value)` 可以确保新添加的属性是响应式的,参数分别是目标对象、属性名或数组索引、新值。
上一篇:vue 获取当前路由
下一篇:vue文件
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站