在項目開發中每一次路由的切換或者頁面的刷新都需要判斷用戶是否已經登錄,前端可以判斷,后端也會進行判斷的,我們前端最好也進行判斷。
vue-router提供了導航鈎子:全局前置導航鈎子 beforeEach和全局后置導航鈎子 afterEach,他們會在路由即將改變前和改變后進行觸發。所以判斷用戶是否登錄需要在beforeEach導航鈎子中進行判斷。
導航鈎子有3個參數:
1、to:即將要進入的目標路由對象;
2、from:當前導航即將要離開的路由對象;
3、next :調用該方法后,才能進入下一個鈎子函數(afterEach)。
next()//直接進to 所指路由
next(false) //中斷當前路由
next('route') //跳轉指定路由
next('error') //跳轉錯誤路由
beforeEach:
路由配置文件:
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import HomePage from '@/pages/home.vue'
Vue.use(Router)
const router=new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},
{
path: '/home',
name: 'home',
component: HomePage
},
{
path:'*',
redirect:'/home'
}
],
})
router.beforeEach((to,from,next)=>{
console.log(to);
console.log(from);
next();
})
export default router;
打印結果如下:
實現用戶驗證的代碼:
1 router.beforeEach((to, from, next) => { 2 //我在這里模仿了一個獲取用戶信息的方法 3 let isLogin = window.sessionStorage.getItem('userInfo'); 4 if (isLogin) { 5 //如果用戶信息存在則往下執行。 6 next() 7 } else { 8 //如果用戶token不存在則跳轉到login頁面 9 if (to.path === '/login') { 10 next() 11 } else { 12 next('/login') 13 } 14 } 15 })
afterEach:
和beforeEach不同的是afterEach不接收第三個參數 next 函數,也不會改變導航本身,一般beforeEach用的最多,afterEach用的少.
router.afterEach((to,from)=>{ //這里不接收next console.log(to); console.log(from); })