在说这个之前我们先看一段代码:
<template>
<div>
<div>
<span>用户名: {{ userInfo.name }}</span>
<span>用户性别: {{ userInfo.sex }}</span>
<span v-if="userInfo.age">
年龄: {{ userInfo.age}}
</span>
</div>
<button @click="addAge()">添加年龄</button>
</div>
</template>
<script>
export default {
data() {
return {
userInfo: {
name: '小明',
sex: '男'
}
}
},
methods: {
// 在这里添加用户的年龄
addAge() {
this.userInfo.age= '25'
}
}
}
</script>
我们预想的是点击按钮添加用户的年龄,但是,实际上我们点击后并没有反应。
这个是什么原因呢?
原因是因为vue的数据响应是基于Object.defineProperty方法把data上的属性转化为getter和setter,所以对于没有在data里面定义的属性是没办法监测到的。
所以在此我们有两种解决方案:
- 使用拷贝的方法
addAge() {
this.userInfo = {
...this.userInfo,
age: "25",
};
},
因为使用拷贝的方法使得userInfo属性改变了所以是可以检测到的。
- 使用vue内置的$set方法修改数据
addAge() {
this.$set(this.userInfo,'age','25')
},