Vue 2 使用 Object.defineProperty 实现响应式,这导致它无法检测到对象属性的直接添加或删除,以及通过索引直接设置数组项的变化。
对象新增属性问题
<template>
<div>
<p>用户信息:{{ user }}</p>
<button @click="addProperty">添加新属性</button>
</div>
</template>
<script>
export default {
data() {
return {
user: {
name: '张三',
age: 25
}
}
},
methods: {
addProperty() {
// 直接添加新属性不会触发视图更新
this.user.gender = '男';
console.log(this.user); // 控制台能看到gender属性,但视图不会更新
// 正确做法:使用Vue.set或this.$set
// this.$set(this.user, 'gender', '男');
}
}
}
</script>
数组通过下标操作问题
<template>
<div>
<p>列表:{{ items }}</p>
<button @click="updateItem">更新第一项</button>
</div>
</template>
<script>
export default {
data() {
return {
items: ['苹果', '香蕉', '橙子']
}
},
methods: {
updateItem() {
// 通过索引直接修改数组项不会触发视图更新
this.items[0] = '西瓜';
console.log(this.items); // 控制台能看到变化,但视图不会更新
// 正确做法:
// 1. 使用Vue.set或this.$set
// this.$set(this.items, 0, '西瓜');
// 2. 使用数组的变异方法
// this.items.splice(0, 1, '西瓜');
}
}
}
</script>