vue路由實現登錄攔截
在項目開發中每一次路由的切換或者頁面的刷新都需要判斷用戶是否已經登錄,前端可以判斷,后端也會進行判斷的,我們前端最好也進行判斷。
vue-router提供了導航鉤子:全局前置導航鉤子 beforeEach和全局后置導航鉤子 afterEach,他們會在路由即將改變前和改變后進行觸發。所以判斷用戶是否登錄需要在beforeEach導航鉤子中進行判斷。
導航鉤子有3個參數:
1、to:即將要進入的目標路由對象;
2、from:當前導航即將要離開的路由對象;
3、next :調用該方法后,才能進入下一個鉤子函數(afterEach)。
next()//直接進to 所指路由next(false) //中斷當前路由next(’route’) //跳轉指定路由next(’error’) //跳轉錯誤路由
二、路由導航守衛實現登錄攔截這里用一個空白的vue項目來演示一下,主要有2個頁面,分別是首頁和登錄。
訪問首頁時,必須要登錄,否則跳轉到登錄頁面。
新建一個空白的vue項目,在srccomponents創建Login.vue
<template> <div>這是登錄頁面</div></template><script> export default { name: 'Login' }</script><style scoped></style>
修改srcrouterindex.js
import Vue from ’vue’import Router from ’vue-router’import HelloWorld from ’@/components/HelloWorld’import Login from ’@/components/Login’Vue.use(Router)const router = new Router({ mode: ’history’, //去掉url中的# routes: [ { path: ’/login’, name: ’login’, meta: { title: ’登錄’, requiresAuth: false, // false表示不需要登錄 }, component: Login }, { path: ’/’, name: ’HelloWorld’, meta: { title: ’首頁’, requiresAuth: true, // true表示需要登錄 }, component: HelloWorld }, ]})// 路由攔截,判斷是否需要登錄router.beforeEach((to, from, next) => { if (to.meta.title) { //判斷是否有標題 document.title = to.meta.title; } // console.log('title',document.title) // 通過requiresAuth判斷當前路由導航是否需要登錄 if (to.matched.some(record => record.meta.requiresAuth)) { let token = localStorage.getItem(’token’) // console.log('token',token) // 若需要登錄訪問,檢查是否為登錄狀態 if (!token) { next({ path: ’/login’, query: { redirect: to.fullPath } }) } else { next() } } else { next() // 確保一定要調用 next() }})export default router;
說明:
在每一個路由中,加入了meta。其中requiresAuth字段,用來標識是否需要登錄。
在router.beforeEach中,做了token判斷,為空時,跳轉到登錄頁面。
訪問首頁
http://localhost:8080
會跳轉到
http://localhost:8080/login?redirect=%2F
效果如下:
打開F12,進入console,手動寫入一個token
localStorage.setItem(’token’, ’12345678910’)
效果如下:
再次訪問首頁,就可以正常訪問了。
打開Application,刪除Local Storage里面的值,右鍵,點擊Clear即可
刷新頁面,就會跳轉到登錄頁面。
怎么樣,是不是很簡單呢!
以上就是vue路由實現登錄攔截的詳細內容,更多關于vue 登錄攔截的資料請關注好吧啦網其它相關文章!
相關文章: