vue-admin 登录权限与路由守卫

使用vue开发后台管理系统,除了路由与页面搭建,最主要的还有登录权限与路由守卫。因为直接使用的vue-admin-element的后台管理系统,其中已经做了登录权限的管理,此次记录是为更好的梳理适合自己项目的流程,以及后续的查看与补充。

vue-admin-element模板地址:https://github.com/PanJiaChen/vue-element-admin

vue-admin-element模板介绍:https://segmentfault.com/a/1190000009275424

关于项目文件目录

这里首先介绍一下相关文件目录,方便后续的路径查看(主要标红)

├── build                      // 构建相关  
├── config                     // 配置相关
├── src                        // 源代码
│   ├── api                    // 所有请求
│   ├── assets                 // 主题 字体等静态资源
│   ├── components             // 全局公用组件
│   ├── directive              // 全局指令
│   ├── filtres                // 全局 filter
│   ├── icons                  // 项目所有 svg icons
│   ├── lang                   // 国际化 language
│   ├── mock                   // 项目mock 模拟数据
│   ├── router                 // 路由
│   ├── store                  // 全局 store管理
│   ├── styles                 // 全局样式
│   ├── utils                  // 全局公用方法
│   ├── vendor                 // 公用vendor
│   ├── views                   // view页面
│   ├── App.vue                // 入口页面
│   ├── main.js                // 入口 加载组件 初始化等
│   └── permission.js          // 权限管理
├── static                     // 第三方不打包资源
│   └── Tinymce                // 富文本
├── .babelrc                   // babel-loader 配置
├── eslintrc.js                // eslint 配置项
├── .gitignore                 // git 忽略项
├── favicon.ico                // favicon图标
├── index.html                 // html模板
└── package.json               // package.json

1、进入系统后首先就是登录功能,这里使用了vuex管理登录信息与用户信息

页面路径:src/views/login/index
  //登录
  handleLogin() {
    //验证登录信息 this.$refs.loginForm.validate(valid => { if (valid) {
      //指向src/store/modules/user.js中的登录方法Login this.$store.dispatch('Login', this.loginForm).then(() => {
       //通过Login后路由定向到首页 this.$router.push({ path: '/' }) }).catch(() => { }) } else { console.log('error submit!!') return false } }) },

2、管理登录与获取用户信息

页面路径:src/store/modules/user.js
  // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim() //去空
      const fd = new FormData() //登录参数
      fd.append('username', username)
      fd.append('password', userInfo.password)
      return new Promise((resolve, reject) => {
        login(fd).then(response => {
          const data = response.data
          setToken(data.token) //存储token信息
          commit('SET_TOKEN', data.access_token)
          resolve()
        }).catch(error => {
          // console.log(5)
          reject(error)
        })
      })
    },

  // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo(state.token).then(response => {
          const data = response.data
      //获取用户权限并存储roles if (data.roles && data.roles.length > 0) { commit('SET_ROLES', data.roles) } else { reject('getInfo: roles must be a non-null array !') } commit('SET_USERNAME', data.username) commit('SET_NICKNAME', data.nickname) resolve(response) }).catch(error => { reject(error) }) }) },

3、请求拦截

页面路径:src/utils/request.js
import axios from 'axios'
// import qs from "qs"
import { Message } from 'element-ui'
import store from '../store'
import { getToken } from '@/utils/auth'
import { apiURL } from '@/api/config/ip-config'
// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 15000 // 请求超时时间
})
// request拦截器
service.interceptors.request.use(
  config => {
    if (getToken()) {
    // 如果存在token,在每个请求头中带上token信息。x-token是自己定义的key,可与后端协商统一 config.headers['X-token'] = getToken() } return config }, error => { // Do something with request error // console.log(error) // for debug Promise.reject(error) } ) // respone拦截器 service.interceptors.response.use( (response) => {
    /**
    *自定义code来标示请求状态
    * 当code返回如下情况则说明权限有问题,登出并返回到登录页
    * 如想通过xmlhttprequest状态码来标识,逻辑可写在下面error中
    */
    const res = response.data
    if (res.code) {
    // 自定义状态码1000为有效,其他值为特殊状态,可结合自己业务进行修改 if (res.code !== 1000) { Message({ message: res.message, type: 'error', duration: 5 * 1000 }) // 50008:非法的token; 50012:其他客户端登录了; 50014:Token 过期了; // if (res.code === 50008 || res.code === 50012 || res.code === 50014) { // MessageBox.confirm( // '你已被登出,可以取消继续留在该页面,或者重新登录', // '确定登出', // { // confirmButtonText: '重新登录', // cancelButtonText: '取消', // type: 'warning' // } // ).then(() => { // store.dispatch('FedLogOut').then(() => { // location.reload() // 为了重新实例化vue-router对象 避免bug // }) // }) // } return Promise.reject('error') } else { return response.data } } else { return response } // return response }, error => { if (typeof (error.response) !== 'undefined') { if (error.response.status === 401) { // MessageBox.alert(error.response.data.message, '提示', { // confirmButtonText: '重新登录', // type: 'warning' // }) Message({ message: error.response.data.message, type: 'info', duration: 5 * 1000 }) setTimeout(function() { store.dispatch('FedLogOut').then(() => { location.reload()// 为了重新实例化vue-router对象 避免bug }) }, 1000) // .then(() => { // }) } else { Message({ message: error.response.data.message, type: 'error', duration: 5 * 1000 }) } } else { Message({ message: error.message, type: 'error', duration: 5 * 1000 }) } return Promise.reject(error) } ) export default service

4、设置路由

页面路径:src/router/index.js
import Vue from 'vue'
import Router from 'vue-router'

// in development-env not use lazy-loading, because lazy-loading too many pages will cause webpack hot update too slow. so only in production use lazy-loading;
// detail: https://panjiachen.github.io/vue-element-admin-site/#/lazy-loading

Vue.use(Router)

/* Layout */
import Layout from '../views/layout/Layout'

/**
* hidden: true                   if `hidden:true` will not show in the sidebar(default is false)
* alwaysShow: true               if set true, will always show the root menu, whatever its child routes length
*                                if not set alwaysShow, only more than one route under the children
*                                it will becomes nested mode, otherwise not show the root menu
* redirect: noredirect           if `redirect:noredirect` will no redirct in the breadcrumb
* name:'router-name'             the name is used by <keep-alive> (must set!!!)
* meta : {
    title: 'title'               the name show in submenu and breadcrumb (recommend set)
    icon: 'svg-name'             the icon show in the sidebar,
  }
**/
export const constantRouterMap = [
  // 基础-路由设置
  { path: '/login', component: () => import('@/views/login/index'), hidden: true },
  { path: '/404', component: () => import('@/views/404'), hidden: true },
  // { path: '*', redirect: '/404', hidden: true },
  {
    path: '',
    component: Layout,
    redirect: 'home',
    children: [{
      path: 'home',
      component: () => import('@/views/home/index'),
      name: 'home',
      meta: { title: '首页', icon: 'table', noCache: true }
    }]
  }
]

export const asyncRouterMap = [
{
  path: '/demo',
  component: Layout,
  redirect: '/demo/demoChild1',
  alwaysShow: true, // will always show the root menu
  name: 'Demo',
  meta: {
    title: '示例',
    icon: 'tree',
    roles: ['admin','demoRoles']
  },
  children: [
    {
      path: 'demoChild1',
      component: () => import('@/views/demo/demoChild1'),
      name: 'DemoChild1',
      meta: {
        title: '示例C1'
      }
    },
    {
      path: 'demoChild2',
      component: () => import('@/views/demo/demoChild2'),
      name: 'DemoChild2',
      meta: {
        title: '示例C2'
      }
    }
  ]
},
{ path: '*', redirect: '/404', hidden: true } // 很重要,如果动态路由,一定要将404页面定义在最后,防止无法匹配页面报错
]
//重置路由
const createRouter = () => new Router({
  // mode: 'history', // require service support
  scrollBehavior: () => ({ y: 0 }),
  routes: constantRouterMap.concat(asyncRouterMap)
  // routes: []
})
const router = createRouter()
export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
}

export default router

5、过滤路由

  如果菜单栏都是前端写死的那就不用考虑这一步。

  但我们在做后台管理系统的时候,通常是根据登录用户所拥有的权限来展示不同的菜单栏。

  所以匹配合适的路由就尤为重要。

 页面路径:src/store/permission.js
  
import { asyncRouterMap, constantRouterMap } from '@/router'
/**
* 引入 src/router/index中定义的asyncRouterMap与constantRouterMap
* constantRounterMap:一般写入基础路由/login、/404等
* asyncRouterMap:写入需配置路由,且由roles管理 /** * 通过meta.role判断是否与当前用户权限匹配 * @param roles * @param route */ function hasPermission(roles, route) { if (route.meta && route.meta.roles) { return roles.some(role => route.meta.roles.indexOf(role) >= 0) } else { return true } } /** * 递归过滤异步路由表,返回符合用户角色权限的路由表 * @param asyncRouterMap * @param roles */ function filterAsyncRouter(asyncRouterMap, roles) { const accessedRouters = asyncRouterMap.filter(route => { if (hasPermission(roles, route)) { if (route.children && route.children.length) { route.children = filterAsyncRouter(route.children, roles) } return true } return false }) return accessedRouters } const permission = { state: { routers: constantRouterMap, addRouters: [] }, mutations: { SET_ROUTERS: (state, routers) => { state.addRouters = routers state.routers = constantRouterMap.concat(routers) } }, actions: { GenerateRoutes({ commit }, data) { return new Promise(resolve => { const { roles } = data let accessedRouters = []
     // 此处可根据业务需求做调整,本项目是admin拥有所有权限 if (roles.indexOf('admin') >= 0) { accessedRouters = asyncRouterMap } else { accessedRouters = filterAsyncRouter(asyncRouterMap, roles) } commit('SET_ROUTERS', accessedRouters) resolve() }) } } } export default permission

6、路由拦截与路由守卫

  在我们拿到用户roles后,通过router.addRoutes动态挂载路由

  页面路径:src/permission.js
import router from './router'
import store from './store' import NProgress from 'nprogress' // Progress 进度条 import 'nprogress/nprogress.css'// Progress 进度条样式 import { Message } from 'element-ui' import { getToken } from '@/utils/auth' // 验权 // 过滤符合条件的路由-可根据自己业务做调整-根据参数 to 做信息判定,如果符合条件,则前往相应页面,否则前往404 function hasPermission(roles, to) { if (roles.indexOf('admin') >= 0) { return true // admin permission passed directly } if (to.meta.roles) { return roles.some(role => to.meta.roles.indexOf(role) >= 0) } else { return true } } const whiteList = ['/login', '/404'] // 不重定向白名单 router.beforeEach((to, from, next) => { NProgress.start() if (getToken()) {
  // 路由守卫 if (to.path === '/login') { next({ path: '/' }) NProgress.done() // if current page is dashboard will not trigger afterEach hook, so manually handle it } else { if (store.getters.roles.length === 0) {
     // 如果权限roles为空,则重新获取用户信息,更新roles store.dispatch('GetInfo').then(res => { // 拉取用户信息 const roles = res.data.roles store.dispatch('GenerateRoutes', { roles }).then(() => { // 根据roles权限生成可访问的路由表 router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表 next({ ...to, replace: true }) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record }) }).catch((err) => { store.dispatch('FedLogOut').then(() => { Message.error(err || 'Verification failed, please login again') next({ path: '/' }) }) }) } else {
     // 如果已存在权限,过滤符合条件的路由,如果不符合,则跳往404页面
     // 此处hasPermission是验证roles是否符合,其中参数to是要跳往的页面路由相关信息,可根据自己业务修改
if (hasPermission(store.getters.roles, to)) { next()// } else { next({ path: '/404', replace: true, query: { noGoBack: true }}) } } } } else { if (whiteList.indexOf(to.path) !== -1) { next() } else { next('/login') NProgress.done() } } }) router.afterEach(() => { NProgress.done() // 结束Progress })

 至此,关于vue-admin的登录与权限基本就这些,当然还有很多其他的方法,这只是当前项目所需,后续有完善再不断补充。

关于vue-admin-element的更多信息可以参考这里:vue-admin-element模板介绍:https://segmentfault.com/a/1190000009275424

猜你喜欢

转载自www.cnblogs.com/liangpi/p/11906207.html
今日推荐