- 普通監(jiān)聽(tīng)
缺點(diǎn):當(dāng)值第一次綁定的時(shí)候愤兵,不會(huì)執(zhí)行監(jiān)聽(tīng)函數(shù)
<input type="text" v-model="age"/>
//監(jiān)聽(tīng) age值發(fā)生變化時(shí)觸發(fā)
watch: {
age(newAge, oldAge) {
console.log(newAge)
}
}
- 第二種寫法
只有當(dāng)值改變的時(shí)候 才會(huì)執(zhí)行,如果想在第一次綁定的時(shí)候執(zhí)行此監(jiān)聽(tīng)函數(shù) 則需要 設(shè)置immediate為true
<input type="text" v-model="age"/>
watch: {
age: {
handler (newAge, oldAge) {
console.log(newAge)
},
immediate: true
}
}
- 深度監(jiān)聽(tīng)
當(dāng)要監(jiān)聽(tīng)對(duì)象或數(shù)組的時(shí)候需要添加deep:true 屬性
<input type="text" v-model="userName.name" />
data (){
return {
userName: {name:'張三'}
}
},
watch: {
userName: {
handler(newName, oldName) {
console.log(newName)
},
immediate: true,
deep: true
}
}