在vue中我們經常會使用/Id/:id 盡管我們改變了id傳入了不同的路由,但我們還是使用的同一個view。
當我們多個路由公用一個組件時,鈎子函數(created和mounted)只會觸發一次,我們如果想要多次觸發,有兩種方法:
第一種方法:
在app.vue中添加:
<router-view :key="key" />
computed: {
key() {
return this.$route.name !== undefined? this.$route.name +new Date(): this.$route +new Date()
}
}
或者
<router-view :key="$route.fullPath"/>
通過一個唯一的Key保證我們每次都能重新刷新路由
但這樣有個缺點:所有的鈎子函數都被觸發了,如果我們只是想要觸發指定的鈎子函數怎么辦?
第二種方法:
watch: { //通過watch來監聽路由變化,每次路由變化都會執行function()
"$route": function(){
this.getData(this.$route.params.category);
}
}