一:同一項目中路由的跳轉
mounted和created都只能執行一次,嘗試監聽改變的數據也未起效果,項目中使用了<keep-alive>,所以用activated監聽初始函數
1.需要跳轉的頁面home.vue: 頁面每次跳轉時都改變參數,通過獲取不同的時間來實現地址如:http://localhost:8080/#/noticeDetail?time=1641284450820

2.路由設置為不緩存上次的數據
{
path: "/noticeDetail",
name: "noticeDetail",
component: pages.noticeDetail,
meta: {
title: "公告信息",
code: "noticeDetail",
noCache:false
}
},
3.跳轉目標頁面noticeDetail.vue實現監聽:
activated(){ //項目使用了keep-alive,所以用activate監聽才會再次刷新數據
this.init();//初始化頁面
},
二、從公共框架中跳轉到同一個路由,直接用this.$router.push()的話因為是同一個頁面會報錯,並且頁面數據也不更新

解決:1.解決頁面報錯 NavigationDuplicated: Avoided redundant navigation to current location: "/",原因是路由重復。
在 router 文件夾下的 index.js 中加入下面代碼,解決!
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
return originalPush.call(this, location).catch(err => err)
}
2.解決路由數據不刷新的問題:先判斷當前路由是否是重復的路由,如果是的話就刪掉重新加載並且再次reload()
會有一個問題就是頁面原先打開的所有的路由都關了 只保留了最后加載的這個路由,目前沒找到好的解決辦法
const time = Date.now();
sessionStorage.setItem('noticeDetail',JSON.stringify(params));
// 先關閉當前頁面再打開解決第二次打不開頁面的問題
if(this.$route.name=="noticeDetail"){
this.store.delView(this.$route); //前面用inject引入store,所以可以這樣寫
this.$router.push({path:'/noticeDetail',query:{time}});
setTimeout(()=>{
location.reload();
},0)
}else{
this.$router.push({path:'/noticeDetail',query:{time}});
}
針對第二種的優化方案:
用watch監聽路由,即使是不同項目之間的跳轉也可以監聽到路由的變化,之后再次調用接口實現頁面刷新數據渲染
watch: {
$route(to) { // 先關閉當前頁面再打開解決第二次打不開頁面的問題
if (this.$route.name=='noticeDetail') { //noticeDetail為當前打開的這個頁面的路由
// console.log("進來panduan");
this.init();//后續業務邏輯處理
}
}
},
