最近用vue做一個新項目,經(jīng)歷了各種折磨,每次遇到問題都想大喊,格勞資上JQuery,氮素肯定是不行的,今天遇到一個小問題,Vue父組件向子組件傳遞一個動態(tài)的值,子組件只能獲取初始值,不能實時更新?
這就有點折磨人了,設(shè)想的是,父組件發(fā)生變化獲取數(shù)據(jù),動態(tài)傳遞給子組件,子組件實時刷新視圖。vue視圖是數(shù)據(jù)驅(qū)動的嘛,這設(shè)想就是完美而合理的了吧。可就是不行?。。?!
請教前輩,支個招讓用vuex,可就是個小功能能,有點殺雞用牛刀啊,又去查了查文檔,找了找資料。原來需要在子組件watch(監(jiān)聽)父組件數(shù)據(jù)的變化。
我就這樣使用watchl啦,
data() {
return {
frontPoints: 0
}
},
watch: {
frontPoints(newValue, oldValue) {
console.log(newValue)
}
}
咦?又出幺蛾子了,完全監(jiān)聽不到嘛!??!
繼續(xù)查文檔,好嘛,原來這種方式只能watch基礎(chǔ)類型的變量,我傳遞的是個object啊,代碼,真的處處是坑。。。
為了防止將來繼續(xù)掉坑,做個總結(jié)吧
1、普通watch
如上所示,用過vue的都應(yīng)該挺熟悉的
2、數(shù)組的watch
data() {
return {
winChips: new Array(11).fill(0)
}
},
watch: {
winChips: {
handler(newValue, oldValue) {
for (let i = 0; i < newValue.length; i++) {
if (oldValue[i] != newValue[i]) {
console.log(newValue)
}
}
},
deep: true
}
}
3、對象的watch
data() {
return {
bet: {
pokerState: 53,
pokerHistory: 'local'
}
}
},
watch: {
bet: {
handler(newValue, oldValue) {
console.log(newValue)
},
deep: true
}
}
tips: 只要bet中的屬性發(fā)生變化(可被監(jiān)測到的),便會執(zhí)行handler函數(shù);
如果想監(jiān)測具體的屬性變化,如pokerHistory變化時,才執(zhí)行handler函數(shù),則可以利用計算屬性computed做中間層。
事例如下:
4、對象的具體屬性watch(活用computed)
data() {
return {
bet: {
pokerState: 53,
pokerHistory: 'local'
}
}
},
computed: {
pokerHistory() {
return this.bet.pokerHistory
}
},
watch: {
pokerHistory(newValue, oldValue) {
console.log(newValue)
}
}