赞
踩
在每一个路由的 meta 属性里,将能访问该路由的角色添加到 roles 里。用户每次登陆后,获取用户的角色。
然后在访问页面时,把路由的 meta 属性和用户的角色进行对比,如果用户的角色在路由的 roles 里,那就是能访问,如果不在就拒绝访问 或者 弹出提示
代码:
- import Vue from 'vue'
- import Router from 'vue-router'
- import HelloWorld from '@/components/HelloWorld'
- import NoAccess from '@/components/NoAccess'
-
- Vue.use(Router)
-
- const router = new Router({
- routes: [
- {
- path: '/',
- name: 'HelloWorld',
- component: HelloWorld,
- meta: {
- roles: ['admain', 'users']
- }
- },
- {
- path: '/NoAccess',
- name: 'NoAccess',
- component: NoAccess
- }
- ]
- })
-
- // 模拟角色
- const userRole = 'users'
-
- // router 是 Router 的实例
- router.beforeEach((to, from, next) => {
- // 说明该路由有权限校验
- if (to.meta.roles) {
- // 校验身份
- if (to.meta.roles.includes(userRole)) {
- next()
- } else {
- next('/NoAccess')
- }
- } else { // 没权限直接跳过
- next()
- }
- })
-
- export default router

网站一般只要登陆过一次后,接下来该网站的其他页面都是可以直接访问的,不用再次登陆。
我们可以通过 token 或 cookie 来实现,下面用代码来展示一下如何用 token 控制登陆验证
也是通过 路由守卫 beforeEach 来实现的
- router.beforeEach((to, from, next) => {
- // 如果有token 说明该用户已登陆
- if (localStorage.getItem('token')) {
- // 在已登陆的情况下访问登陆页会重定向到首页
- if (to.path === '/login') {
- next({path: '/'})
- } else {
- next({path: to.path || '/'})
- }
- } else {
- // 没有登陆则访问任何页面都重定向到登陆页
- if (to.path === '/login') {
- next()
- } else {
- next(`/login?redirect=${to.path}`)
- }
- }
- })

用户根据不同的角色生成相应的路由列表
router.addRoutes(routerArrayConfig)
代码:
- const router = new Router({
- routes: [
- {
- path: '/login',
- name: 'login',
- component: () => import('../components/Login.vue')
- },
- {
- path: '/',
- redirect: '/home'
- component: () => import('../components/Home.vue')
- },
- ]
- })
与下方相同:
- const router = new Router({
- routes: [
- {
- path: '/',
- redirect: '/home'
- },
- ]
- })
-
- router.addRoutes([
- {
- path: '/login',
- name: 'login',
- component: () => import('../components/Login.vue')
- }
- ])

所以可能后端返回 一个列表,前端通过数组循环等处理方式,变成真正的路由导入
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。