1.对象变更监测
🍊问题场景:
- 如果异步请求回包的数据中,需要在原来没有的
data的user对象中添加新的属性,并能让这个属性支持动态响应的,那么方法有2个
- 通过
Vue.$set(object,key,value)添加响应式属性--如- this.$set( this.user, 'age' , 20 );设置了user的之前没有的age属性。
- 可以通过
Object.assign()去添加一个或者多个属性
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
<h3>
{{user.name}},{{user.age}},{{user.phone}}
<button @click='handlerAdd'>添加属性</button>
</h3>
</div>
<script src="./vue.js"></script>
<script>
new Vue({
el:"#app",
data:{
user:{}
},
methods: {
handlerAdd() {
this.user = Object.assign({},this.user,{
age:20,
phone:18511803134
})
}
},
created(){
setTimeout(() => {
this.user = {
name:"张三"
}
}, 1250);
}
})
</script>
</body>
</html>