- A+
所属分类:Web前端
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