vue在App.vue檔案中監聽路由變化重新整理頁面操作
阿新 • • 發佈:2020-08-14
在路由跳轉時,會出現頁面需要重新重新整理一遍才能獲取資料載入頁面,這時新增一個監聽器,如果跳轉到頁面重新整理一次。
export default { name: 'App',provide(){ return{ reload:this.reload } },data(){ return { isRouterAlive:true,} },//監聽器 watch: { // 方法1 '$route' (to,from) { //監聽路由是否變化 // console.log(999) if(to.path == "/"){ //跳轉到哪個頁面 location.reload() } },},methods:{ reload(){ this.isRouterAlive = false; this.$nextTick(function () { this.isRouterAlive = true }); },}
補充知識:vue監聽路由的改變和監聽頁面的重新整理與離開
要分清兩者的區別。
首先是監聽頁面的重新整理與離開,此時相當於直接在這個網頁中按了重新整理,如果是webapp則是離開這個app而不是切換路由!
如果是用js的特性監測,則是不僅可以頁面的重新整理與離開,還能切換路由。注意當keepalive時即使切換了路由也無效。
在script中直接增加監聽器監視beforeunload:
//監視如果頁面離開 created() { window.addEventListener('beforeunload',this.updateHandler) },beforeDestroy() { this.finalItemDetail(); // 自己要進行的操作 },destroyed() { window.removeEventListener('beforeunload',
然後methods中新增finalItemDetail和updateHandler方法:
updateHandler() { this.finalItemDetail() },finalItemDetail() { console.log('重新整理或關閉'); },
如果想監聽某個特定的頁面的離開,比如我現在在/index下,現在去了/index/001下面,就可以在watch中監聽路由的變化,前提是實用vue-router。
如果是簡單的判斷路由變化可以用註釋掉的,直接執行clear方法(自己定義在methods中)
但是注意這個只能監聽自己子路由的變化!
watch: { // 如果路由有變化,會再次執行clear方法 // "$route": "clear",$route(to,from){ console.log( to.path,from.path ); this.clear(to.path); } },
然後我還額外做了個判斷:
clear(path) { if(path!="/item/item01/evaluate") console.log("從這個頁面離開了"); this. active=0; },
以上這篇vue在App.vue檔案中監聽路由變化重新整理頁面操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。