本文是在該項(xiàng)目中踩坑得出的結(jié)論:
今天在自己寫的vue項(xiàng)目中,由于路由跳轉(zhuǎn)需要更改vuex狀態(tài)中的title劳淆,因此監(jiān)聽了路由的path链沼,下面是代碼:
watch: {
'$route.path': (newVal, oldVal) => {
if (newVal == '/home') {
this.updateHomeTitle();
} else if (newVal == '/discovery') {
this.updateDiscoveryTitle();
} else if (newVal == '/collect') {
this.updateCollectTitle();
}
}
},
methods: {
updateHomeTitle() {
this.$store.commit('UPDATE_TITLE', this.sHomeTitle);
},
updateDiscoveryTitle() {
this.$store.commit('UPDATE_TITLE', this.sDiscoveryTitle);
},
updateCollectTitle() {
this.$store.commit('UPDATE_TITLE', this.sCollectTitle);
}
}
點(diǎn)擊底部的tabBar的時(shí)候,一直報(bào)錯(cuò):
后來經(jīng)過查證后沛鸵,發(fā)現(xiàn)尤大大在官方文檔已經(jīng)提及https://cn.vuejs.org/v2/api/#watch
注意括勺,不應(yīng)該使用箭頭函數(shù)來定義 watcher 函數(shù) (例如 searchQuery: newValue => this.updateAutocomplete(newValue))。理由是箭頭函數(shù)綁定了父級(jí)作用域的上下文曲掰,所以 this 將不會(huì)按照期望指向 Vue 實(shí)例疾捍,this.updateAutocomplete 將是 undefined。
這就是問題所在了栏妖,this綁定的是上線文乱豆,而不是組件,所以才會(huì)找不到方法