全局前置守衛
router.beforeEach((to, from, next) => {
// ...
})
每個守衛方法接收三個參數:
to
: 即將要進入的目標路由對象from
: 當前導航正要離開的路由-
next
: 一定要調用該方法來 resolve 這個鉤子。執行效果依賴next
方法的調用參數。-
next()
: 進行管道中的下一個鉤子。如果全部鉤子執行完了,則導航的狀態就是confirmed
(確認的)。 -
next(false)
: 中斷當前的導航。如果瀏覽器的URL
改變了 (可能是用戶手動或者瀏覽器后退按鈕),那么URL
地址會重置到from
路由對應的地址。 -
next('/')
或者next({ path: '/' })
: 跳轉到一個不同的地址。當前的導航被中斷,然后進行一個新的導航。你可以向next
傳遞任意位置對象,且允許設置諸如replace: true
、name: 'home'
之類的選項以及任何用在router-link
的to
prop 或router.push
中的選項。 -
next(error)
: (2.4.0+) 如果傳入next
的參數是一個Error
實例,則導航會被終止且該錯誤會被傳遞給router.onError()
注冊過的回調。
-
登錄鑒權(需要在登錄成功的時候修改跳轉邏輯)
router.beforeEach((to, from, next) => {
document.title=to.meta.title //設置當前頁的title
if (to.matched.some(record => record.meta.auth)) {
if (localStorage.getItem('access_token')) {
next()
} else {
if (to.name === 'Login') {//防止next無限循環的問題
next();
return
}
next({
path: '/Login',
query: {
redirect: to.fullPath
}
});
}
} else {
next()
}
})
登錄成功返回將要跳轉的頁面且返回上一頁不是登錄頁
api.login().then((res) => {
if (res.success) {
localStorage.setItem("access_token", res.token);
//有redirect登錄成功返回將要跳轉的頁面且返回上一頁不是登錄頁
let redirect=this.$route.query.redirect;
redirect ? this.$router.replace(redirect) : this.$router.push("/");
//或者 登錄頁直接登錄,登錄成功返回將要跳轉的頁面且返回上一頁不是登錄頁
let redirect=this.$route.query.redirect || '/';
this.$router.replace(redirect);
}
});
不需要在登錄成功中處理跳轉
router.beforeEach((to, from, next) => {
document.title = to.meta.title
if (to.matched.some(record => record.meta.auth)) {
if (localStorage.getItem('access_token')) {
if (Object.keys(from.query).length === 0) {//判斷路由來源是否有query,處理不是目的跳轉的情況
next()
} else {
let redirect = from.query.redirect//如果來源路由有query
if (to.fullPath === redirect) {//這行是解決next無限循環的問題
next()
} else {
next({ path: redirect, replace: true })//跳轉到目的路由
}
}
} else {
if (to.name === 'Login') {
next();
return
}
next({
path: '/Login',
query: {
redirect: to.fullPath
}
});
}
} else {
next()
}
})
直接登錄頁登錄成功跳轉到將要去的界面點擊瀏覽器返回上一頁不是登錄頁
this.$router.replace('/')