問題/需求:
- 登錄后回傳到上一次的訪問頁面
- 如果上個頁面是其他網站,回傳個人中心(自己定)
解決方案一:
思路: 回應攔截器配合本地存盤,先將網站的域名或基地址存到本地,登錄成功后從本地取出該值進行判斷,匹配則回傳上一頁,否則跳轉到個人中心或網站主頁(自己定)
代碼實作:
回應攔截器: localStorage.setItem("baseURL", "http://127.0.0.1:8080")
// 添加回應攔截器
axios.interceptors.response.use(function (response) {
// 對回應資料做點什么
if (response.data.message === '用戶資訊驗證失敗') {
// this.$router.push({name:'Login'})
localStorage.setItem("baseURL", "http://127.0.0.1:8080")
window.location.href = '#/login'
}
return response;
}, function (error) {
// 對回應錯誤做點什么
return Promise.reject(error);
})
登錄頁:
const baseURL = localStorage.getItem("baseURL");
if (baseURL === "http://127.0.0.1:8080") {
// 匹配基地址成功,移除本地存盤的基地址, 跳轉到上一頁
localStorage.removeItem("baseURL");
this.$router.go(-1);
} else {
// 匹配失敗,跳轉到 個人中心頁
this.$router.push({ path: `personal/${res.data.data.user.id}` });
}
補充: 解決用戶從本網站跳轉到登陸頁,卻不登錄,下次又重其他網站直接導航欄輸入地址跳轉時的bug.
beforeunload: 視窗關倍訓者重新重繪都會觸發這個事件
mounted() {
window.addEventListener("beforeunload", () =>
localStorage.removeItem("baseURL")
);
},
解決方案二:
思路:使用 beforeRouteEnter 導航守衛,將 from:導航正要離開的路由的引數,通過next((vm) => (vm.fromRouteName = from.name)) 將一個值掛載到組件實體fromRouteName屬性上,登錄成功跳轉前判斷 fromRouteName 的值是否存在, 1.存在:即說明上一個頁面是本網站的頁面,可以回傳上一頁. 2.不存在:說明上一個不是本網站的頁面,要跳轉到個人中心或網站主頁
代碼實作:
1.注意點:beforeRouteEnter是跟el,data同級的,其余引數說明看注釋,代碼就一句
beforeRouteEnter(to, from, next) {
console.log("to", to); // 即將要進入的目標 路由物件
console.log("from", from); // 當前導航正要離開的路由
console.log("next", next); // next: Function,next不同用法不同效果,
// 1.next()進行管道中的下個鉤子
// 2.next(false)中斷當前導
// 3.next('/') 或者 next({ path: '/' })中斷本次導航,調到定義的其他導航
// 4.next(error)導航會被終止且該錯誤會被傳遞給 router.onError() 注冊過的回呼
// 在渲染該組件的對應路由被 confirm 前呼叫
// 不!能!獲取組件實體 `this`
// 因為當守衛執行前,組件實體還沒被創建
//
next((vm) => (vm.fromRouteName = from.name));
},
- 在data中定義
fromRouteName
data() {
return {
fromRouteName: null,
};
},
- 在登錄請求成功后,跳轉前判斷
if (this.fromRouteName) {
// 存在該資料,說明上一頁是本網站頁面,執行回傳到上一頁
this.$router.back();
} else {
// 不存在該資料, 說明上一頁不是本網站,執行跳轉到個人中心或主頁
this.$router.push({ path: `personal/${res.data.data.user.id}` });
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/193529.html
標籤:其他
上一篇:前端面試題總結
下一篇:前端學習路線
