全局前置守衛(wèi)
router.beforeEach((to, from, next) => {
// ...
})
每個守衛(wèi)方法接收三個參數(shù):
to
: 即將要進(jìn)入的目標(biāo)路由對象from
: 當(dāng)前導(dǎo)航正要離開的路由-
next
: 一定要調(diào)用該方法來 resolve 這個鉤子。執(zhí)行效果依賴next
方法的調(diào)用參數(shù)昼捍。-
next()
: 進(jìn)行管道中的下一個鉤子。如果全部鉤子執(zhí)行完了殿怜,則導(dǎo)航的狀態(tài)就是confirmed
(確認(rèn)的)属划。 -
next(false)
: 中斷當(dāng)前的導(dǎo)航。如果瀏覽器的URL
改變了 (可能是用戶手動或者瀏覽器后退按鈕)右犹,那么URL
地址會重置到from
路由對應(yīng)的地址急侥。 -
next('/')
或者next({ path: '/' })
: 跳轉(zhuǎn)到一個不同的地址砌滞。當(dāng)前的導(dǎo)航被中斷侮邀,然后進(jìn)行一個新的導(dǎo)航。你可以向next
傳遞任意位置對象贝润,且允許設(shè)置諸如replace: true
绊茧、name: 'home'
之類的選項以及任何用在router-link
的to
prop 或router.push
中的選項。 -
next(error)
: (2.4.0+) 如果傳入next
的參數(shù)是一個Error
實例打掘,則導(dǎo)航會被終止且該錯誤會被傳遞給router.onError()
注冊過的回調(diào)华畏。
-
登錄鑒權(quán)(需要在登錄成功的時候修改跳轉(zhuǎn)邏輯)
router.beforeEach((to, from, next) => {
document.title=to.meta.title //設(shè)置當(dāng)前頁的title
if (to.matched.some(record => record.meta.auth)) {
if (localStorage.getItem('access_token')) {
next()
} else {
if (to.name === 'Login') {//防止next無限循環(huán)的問題
next();
return
}
next({
path: '/Login',
query: {
redirect: to.fullPath
}
});
}
} else {
next()
}
})
登錄成功返回將要跳轉(zhuǎn)的頁面且返回上一頁不是登錄頁
api.login().then((res) => {
if (res.success) {
localStorage.setItem("access_token", res.token);
//有redirect登錄成功返回將要跳轉(zhuǎn)的頁面且返回上一頁不是登錄頁
let redirect=this.$route.query.redirect;
redirect ? this.$router.replace(redirect) : this.$router.push("/");
//或者 登錄頁直接登錄,登錄成功返回將要跳轉(zhuǎn)的頁面且返回上一頁不是登錄頁
let redirect=this.$route.query.redirect || '/';
this.$router.replace(redirect);
}
});
不需要在登錄成功中處理跳轉(zhuǎn)
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尊蚁,處理不是目的跳轉(zhuǎn)的情況
next()
} else {
let redirect = from.query.redirect//如果來源路由有query
if (to.fullPath === redirect) {//這行是解決next無限循環(huán)的問題
next()
} else {
next({ path: redirect, replace: true })//跳轉(zhuǎn)到目的路由
}
}
} else {
if (to.name === 'Login') {
next();
return
}
next({
path: '/Login',
query: {
redirect: to.fullPath
}
});
}
} else {
next()
}
})
直接登錄頁登錄成功跳轉(zhuǎn)到將要去的界面點擊瀏覽器返回上一頁不是登錄頁
this.$router.replace('/')