1、person内的数据改变,不会执行watch监听事件。即watch不能监听复杂数据类型。
需要深度解析才可以。
<body>
<div id="app">
<div>FullName: {{person.fullName}}</div>
<div>firstName: <input type="text" v-model="person.firstName"></div>
</div>
<script>
const vm = new Vue({
el: "#app",
data() {
return {
person: {
firstName: "meihui",
lastName: "xin",
fullName: ''
}
}
},
watch: {
person: {
handler(newval, oldval) {
console.log(newval);
console.log(oldval);
this.person.fullName = this.person.firstName + this.person.lastName;
}
}
}
})
</script>
</body>
2、深度解析加上deep:true后,内部代码已经可以执行了,但是会发现新值与老值是一样的。
watch: {
person: {
handler(newval, oldval) {
console.log(newval);
console.log(oldval);
this.person.fullName = this.person.firstName + this.person.lastName;
},
deep:true
}
}
3.
computed:{
person2(){
return JSON.parse(JSON.stringify(this.person))
}
},
watch: {
person2: {
handler(newval, oldval) {
console.log(newval.firstName);
console.log(oldval.firstName);
this.person.fullName = this.person.firstName + this.person.lastName;
},
deep:true
}
}