Vue路由导航守卫控制页面访问权限
import Vue from 'vue' import VueRouter from 'vue-router' import Login from '../components/login.vue' import Home from '../components/Home.vue' Vue.use(VueRouter) const routes = [{ path: '/', redirect: "/login" }, { path: '/login', component: Login }, { path: '/home', component: Home } ] const router = new VueRouter({ routes }) //挂载路由守卫 router.beforeEach((to, from, next) => { //to要跳转的路径 //from代表从那个路径跳转而来 //next是一个函数,表示放行 //next() 直接放行 next('/login') 表示强制跳转 //如果用户访问登录页,不用判断,直接放行 if (to.path === '/login') return next(); //获取token const tokenStr = window.sessionStorage.getItem("token"); //如果没有token 就证明没有登录,就强制跳转到登录页 if (!tokenStr) return next('/login'); //如果token存在,就直接放行 next(); }); export default router
本人存档:
router.beforeEach((to, from, next) => { document.title = `${to.meta.title} | 测试`; if (to.meta.requireAuth === false) return next(); const role = localStorage.getItem('ms_username'); if (to.meta.requireAuth === true){ if (!role) return next('/login') next() }