vue可以通過watch監(jiān)聽data內(nèi)數(shù)據(jù)的變化柔滔。通常寫法是:
new Vue({
data: {
a: 100幅虑,
msg:{
channel:'音樂',
style:'活潑'
}
},
watch: {
a: function (newval, oldVal) {
console.log('new: %s, old: %s', newval, oldVal)
}
}
})
但是如果你要監(jiān)聽的數(shù)據(jù)是對(duì)象內(nèi)的某一屬性劳澄,直接watch對(duì)象的屬性(eg:msg.channel)就會(huì)報(bào)錯(cuò)
而監(jiān)聽整個(gè)對(duì)象的時(shí)候(eg:msg)會(huì)發(fā)現(xiàn)無論何時(shí)newval和oldVal的值都是一樣的童本,這是因?yàn)閙sg這個(gè)對(duì)象的指向并沒有發(fā)生改變摄职,所以需要深度監(jiān)測
watch: {
msg: {
handler(newValue, oldValue) {
console.log(newValue)
},
deep: true
}
}
如果監(jiān)聽對(duì)象內(nèi)的某一具體屬性,可以通過computed做中間層來實(shí)現(xiàn)
computed: {
channel() {
return this.msg.channel
}
},
watch:{
channel(newValue, oldValue) {
console.log('new: %s, old: %s', newval, oldVal)
//這里面可以執(zhí)行一旦監(jiān)聽的值發(fā)生變化你想做的操作
}
}