前端动态路由(前端控制全部路由,用户角色由后端返回)

与后台控制路由的方式进行对比:
缺点

  1. 前端鉴权不够灵活,线上版本每次修改权限页面,都需要重新打包项目
  2. 中小型项目中 前端鉴权明显更加好用,成本更低,程序员们也不用996了(雾),但是对于权限等级很多,并且比较大的项目,维护这一套鉴权路由,毫无疑问是一个大工程,并且面对频繁变更的需求,bug会出现的更加频繁,前端工程师工作量大大增加,这时候似乎前端鉴权就不再是好的方案
  3. 如果需要在页面中增加角色并且控制可以访问的页面,则不能用前端鉴权

优点:
1.不用后端帮助,路由表维护在前端
2.逻辑相对比较简单,比较容易上手
3.权限少的系统用前端鉴权更加方便

实现关键步骤

1.前端定义静态路由和动态路由
2.登录时请求接口请求用户信息,将其存入vuex中,并且将token存储
3.在路由拦截器中,通过token去请求用户的角色,根据用户的角色,去筛选中用户所拥有的路由,最后使用router.addRoutes将其添加到静态路由中
4.退出登录时清空用户信息,用户角色以及用户的路由

步骤一:前端定义静态路由和动态路由

import Vue from "vue"
import VueRouter from "vue-router"
import Layout from "@/layout"

Vue.use(VueRouter)

// 解决重复点击路由报错的BUG
// 下面这段代码主要解决这个问题 :Uncaught (in promise) Error: Redirected when going from "/login" to "/index" via a navigation guard.
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err)
}

// 定义好静态路由
export const constantRoutes = [
  {
    path: "/login",
    name: "login",
    component: () => import("../views/login"),
    hidden: true,
  },
]

// 定义动态路由,以及每个页面对应的roles(写在meta中,不写代表都可以访问)
export const asyncRoutes = [
  {
    id: 1,
    name: "/",
    path: "/",
    component: Layout,
    redirect: "/index",
    hidden: false,
    children: [
      {
        name: "index",
        path: "/index",
        meta: { title: "index" },
        component: () => import("@/views/index"),
      },
    ],
  },
  {
    id: 2,
    name: "/form",
    path: "/form",
    component: Layout,
    redirect: "/form/index",
    hidden: false,
    children: [
      {
        name: "/form/index",
        path: "/form/index",
        meta: { title: "form" },
        component: () => import("@/views/form"),
      },
    ],
  },
  {
    id: 3,
    name: "/example",
    path: "/example",
    component: Layout,
    redirect: "/example/tree",
    meta: { title: "example" },
    hidden: false,
    children: [
      {
        name: "/tree",
        path: "/example/tree",
        meta: { title: "tree" },
        component: () => import("@/views/tree"),
      },
      {
        name: "/copy",
        path: "/example/copy",
        meta: { title: "copy" },
        component: () => import("@/views/tree/copy"),
      },
    ],
  },
  {
    id: 4,
    name: "/table",
    path: "/table",
    component: Layout,
    redirect: "/table/index",
    hidden: false,
    meta: { roles: ["admin"] },
    children: [
      {
        name: "/table/index",
        path: "/table/index",
        meta: { title: "table", roles: ["admin"] },
        component: () => import("@/views/table"),
      },
    ],
  },
  {
    id: 5,
    name: "/admin",
    path: "/admin",
    component: Layout,
    redirect: "/admin/index",
    hidden: false,
    meta: { roles: ["admin"] },
    children: [
      {
        name: "/admin/index",
        path: "/admin/index",
        meta: { title: "admin", roles: ["admin"] },
        component: () => import("@/views/admin"),
      },
    ],
  },
  {
    id: 6,
    name: "/people",
    path: "/people",
    component: Layout,
    redirect: "/people/index",
    hidden: false,
    meta: { roles: ["admin", "common_user"] },
    children: [
      {
        name: "/people/index",
        path: "/people/index",
        meta: { title: "people", roles: ["admin", "common_user"] },
        component: () => import("@/views/people"),
      },
    ],
  },
  {
    id: 7,
    name: "/404",
    path: "/404",
    component: () => import("@/views/404"),
  },
  // 404 page must be placed at the end !!!
  { path: "*", redirect: "/404", hidden: true },
]

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes: constantRoutes,
})

export default router

注意点:注意404页面要放到最后

步骤二:登录时请求接口请求用户信息,将其存入vuex中,并且将token存储

methods: {
    login () {
      this.$refs.userForm.validate((valid) => {
        if (valid) {
          // 模拟登录接口去请求用户数据
          setTimeout(() => {
            // 这里的res就是模拟后台返回的用户数据(不包含用户角色,一般角色是由单独的一个接口返回)
            const res = dynamicUserData.filter((item) => item.username === this.user.username)[0]
            console.log(res)
            // 存储用户的信息及token到vuex,并做sessionStorage持久化处理
            this.$store.commit('User/saveUserInfo', res)
            Message({ type: 'success', message: "登录成功", showClose: true, duration: 3000 })
            this.$router.push({ path: "/index" })
          }, 1000)
        } else return false
      })
    }
  }

步骤三(关键):在路由拦截器中,通过token去请求用户的角色,根据用户的角色,去筛选中用户所拥有的路由,最后使用router.addRoutes将其添加到静态路由中

路由钩子逻辑:
是否为白名单页面
    是:直接进入
    不是:判断是否有token
            无token:重置到login页面
            有token: 判断用户是否有角色权限列表
                    有权限列表:直接进入
                    没有权限列表:调接口去获取用户权限列表,并将用户权限列表存储到vuex
                                            根据返回的角色权限列表去过滤异步路由中该角色可访问的页面
                                            使用route.addRouters将可访问的路由页面添加进去

import router from './index'
import NProgress from 'nprogress' // progress bar
import store from '@/store'
import menu from '@/mock/menu.js'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

// 白名单页面直接进入
const whiteList = ['/login']

router.beforeEach((to, from, next) => {
  NProgress.start()
  // 白名单页面,不管是否有token,是否登录都直接进入
  if (whiteList.indexOf(to.path) !== -1) {
    next()
    return false
  }
  // 有token(代表了有用户信息,但是不确定有没有角色权限数组)
  if (store.state.User.token) {
    // 判断当前用户是否有角色权限数组, 是登录状态则一定有路由,直接放行,不是登录状态则去获取路由菜单登录
    // 刷新时hasRoles会重置为false,重新去获取 用户的角色列表
    const hasRoles = store.state.permission.roles && store.state.permission.roles.length > 0
    if (!hasRoles) {
      setTimeout(async () => {
        const roles = menu.filter(item => item.token === store.state.User.token)[0].roles
        // 将该角色权限数组存储到vuex中
        store.commit('permission/setRoles', roles)
        // 根据返回的角色信息去过滤异步路由中该角色可访问的页面
        const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
        // dynamically add accessible routes
        router.addRoutes(accessRoutes)
        // hack方法
        next({ ...to, replace: true })
      }, 500)
    } else {
      next() //当有用户权限的时候,说明所有可访问路由已生成 如访问没权限的全面会自动进入404页面
    }
  } else {
    next({ path: '/login' })
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})

步骤三补充点:vuex中做的事为: 将定义好的动态路由 通过 角色权限数组(后台返回的)进行过滤,过滤出用户有的路由,然后将该过滤后的路由添加到静态路由后面去。

import { asyncRoutes, constantRoutes } from '@/router'
/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })
  return res
}

function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    console.log(roles.some(role => route.meta.roles.includes(role)))
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

const state = {
  roles: [],
  routes: [],
  addRoutes: [],
}
const mutations = {
  setRoles(state, val) {
    state.roles = val
  },
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
}
const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      let accessedRoutes
      if (roles.includes('admin')) {
        accessedRoutes = asyncRoutes || []
      } else {
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  },
}
export default {
  namespaced: true,
  state,
  mutations,
  actions,
}

步骤四:退出登录时清空用户信息,用户角色以及用户的路由

methods: {
    // 退出登录
    handleLogout() {
      window.localStorage.removeItem("token")
      // 清除用户信息
      this.$store.commit("User/removeUserInfo")
      // 清除角色权限列表
      this.$store.commit("permission/setRoles", [])
      // 清除角色权限数组
      this.$store.commit("permission/SET_ROUTES", [])
      Message({
        type: "success",
        message: "退出登录",
        showClose: true,
        duration: 3000,
      })
      this.$router.push({ path: "/login" })
    },
  },

文章参考:花裤衩大佬:https://juejin.cn/post/6844903478880370701#heading-4
本文的demo:https://github.com/rui-rui-an/front_router

  • 2
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值