##vue路由守衛用於登錄驗證許可權攔截 ###vue路由守衛 - 全局(router.beforeEach((to, from, next) =>來判斷登錄和路由跳轉狀態) ###主要方法: to:進入到哪個路由去 from:從哪個路由離開 next:路由的控制參數,常用的有next(true)和n ...
vue路由守衛用於登錄驗證許可權攔截
vue路由守衛 - 全局(router.beforeEach((to, from, next) =>來判斷登錄和路由跳轉狀態)
主要方法:
- to:進入到哪個路由去
- from:從哪個路由離開
- next:路由的控制參數,常用的有next(true)和next(false)
首先判斷進入的是否是login頁面?然後再判斷是否已經登陸?
已經登陸了就進入你要跳轉的頁面,沒登錄就進入login頁面
router路由設置
index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
Vue.use(VueRouter)
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
return originalPush.call(this, location).catch(err => err)
}
const routes = [
{
path: '/',
name: 'login',
component: ()=>import('../views/Login/LoginView.vue')
},
{
path: '/register',
name: '註冊',
component: ()=>import('../views/Register/RegisterView.vue')
},
{
path: '/index',
name: 'index',
component: ()=>import('../views/Index/Index.vue'),
// redirect:'/manage',
children:[
{
path: '/manage',
name: '圖書管理',
component: ()=>import('../views/Manage/Manage.vue')
},
]
},
{
path: '/about',
name: 'about',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
}
]
const router = new VueRouter({
routes
});
router.beforeEach((to, from, next) => {
const isLogin = window.localStorage.getItem('main'); //獲取本地存儲的登陸信息
console.log(isLogin)
console.log("to:"+to.name) //進入到哪個路由去
console.log("from:"+from) //從哪個路由離開
//next:路由的控制參數,常用的有next(true)和next(false)
//next() 直接進to 所指路由
//next('route') 跳轉指定路由
if (to.name == 'login') { //判斷是否進入的login頁
if (isLogin) { //判斷是否登陸
next({ name: 'index' }); //已登錄,跳轉首頁
} else {
next(); //沒登錄,繼續進入login頁
}
} else { //如果進入的非login頁
if (isLogin) { //同樣判斷是否登陸
next(); //已登錄,正常進入當前頁面
} else {
next({ name: 'login'}); //沒登錄,跳轉到login頁
}
}
});
export default router