1. 程式人生 > 實用技巧 >vue中的watch監聽

vue中的watch監聽

watch(偵聽器,監聽)

watch監聽,監聽資料的變化
一、淺監聽
它可以監聽字串、普通陣列的變化
watch:{
val(newVal,oldVal){
//實時監控資料的變化
}
}
二、深度監聽
可以監聽到物件的變化,還可以複雜陣列
watch:{
物件:{
deep:true,//深度
handler(新值newVal){
//可以實時監聽到新值newVal的變化
}
}
}
淺監聽
<input type="text" v-model='food[1]'>{{food[1]}}

watch:{
food(newVal,oldVal){
console.log(newVal,'new')
console.log(oldVal,'old')
},
}
深度監聽
    <input type="text" v-model='obj.name'>{{obj.name}}
<hr>
<input type="text" v-model='songList[0].name'>{{songList[0].name}}
watch:{
obj:{
deep:true,//deep 深度
handler(newVal){
console.log(newVal,'new')
console.log(newVal.name,'new')
}
},
songList:{
deep:true,
handler(newVal){
console.log(newVal[0].name,'new')
}
},
}

深度監聽可能會造成頁面卡頓,非必要儘量少的去使用