在項目開發中客戶突然提出這樣的一個需求,客戶需要在查看某一個頁面時,這個頁面需要登錄才能查看評論或者提交問題,或者…等,需要有權限的才能查看的信息,這時客戶會點擊登錄界面,但是登錄後又跳轉到剛剛瀏覽的那個頁面,而不是首頁,之前設計的是直接登錄後,返回到用戶中心,面對這種需求,這種問題該如何去做呢?
1、router.currentRoute:當前的路由信息對象,我們可以通過router.currentRoute.fullPath獲得解析後的 URL,包含查詢參數和 hash 的完整路徑,如果要訪問的頁面的路由有命名(name)的話,可以通過router.currentRoute.name獲得當前路由的名稱。
2、router.replace:作用和router.push相同,不過它不會向history添加新紀錄,而是替換當前的history記錄。
簡單介紹一下解決的思路:
1、首先,我們要把當前的這個路徑保存起來,然後在下一步,用戶需要登錄的時候,直接用這個路由跳轉到這個當前的路由就可以。
main.js
router.beforeEach((to, from, next) => {
if (to.path == '/login') {
//保存當前路由
localStorage.setItem("preRoute", router.currentRoute.fullPath)
}
next()
})
登錄界面 login.vue
this.$store.dispatch("Login", this.loginForm).then(response => {
if (response.code == 200) {
const curr = localStorage.getItem('preRoute')
if (curr == null) {
this.$router.push({ path: "/user_center" });
} else {
this.$router.push({ path: curr });
}
this.$message({ message: response.msg, type: "success", "duration": 1000 });
} else {
this.$message.error(response.msg);
}
}).catch((response) => {
this.$message.error('請聯繫管理員!!!');
});