怎么写一个有权限的后台管理系统

426 阅读3分钟

已完成功能:

  • 登录,超过时间退出登录
  • 不同账号不同权限
  • 在未登录的时候,手动输入url返回登录页
  • 登录后,手动输入非路由内的url返回404页
  • 退出登录

登录

  1. 点击登录按钮的时候,调用vuex里面action的登录方法,返回token,将token存入state里面,并且存放sessionStorage,以防刷新后vuex的数据丢失,同时设置axios的封装方法里面的header请求头的token
// vuex里面
Login({ commit }, userInfo) {
  userInfo.username = userInfo.username.trim();
  console.log(userInfo)
  return new Promise((resolve, reject) => {
    loginFun( userInfo ).then((response: any) => {
      const token = response.data.token;
      // 存储token
      setCookie('token', token, 1);
      // 修改state里面token
      commit('SET_TOKEN', token);
      resolve();
    }).catch((error: any) => {
      reject(error)
    })
  })
},

权限

  1. 使用vue-router的全局钩子router.beforeEach在main.js里面做统一操作,先判断是否有token,如果没有直接返回登录页,如果有执行以下步骤;判断是否获取用户权限列表,如果没获取,则调用获取接口
// main.js
router.beforeEach((to: any, from: any, next) => {
  console.log('main to: ', to.path);
  if(store.state.token) {
    if(to.path == '/login'){
      next({path: '/'});
    } else {
      if(store.getters.GetRoles.length == 0){
      //   // 调用获取权限的接口
        RolusFun(store.state.token).then((response: any) => {
          // console.log('获取的角色数据:', response);
          const roles = response.data;
          // 将获取成功的用户角色传到vuex里面,以供生成侧边栏
          store.dispatch('HandleRoute', roles).then(() => {
            router.addRoutes(store.state.asynaRoles) // 动态添加可访问路由表
            next({ ...to, replace: true }) // 有问题 
            
          })
        }).catch((error: any) => {
          Message({
            message: '获取失败',
            type: "error"
          });
        })
      } else {
        next(); 
      }
    }
  } else {
    // 这里需要注意的时候,next('/login')重置到登录页面,会重新调用router.beforeEach,如果不加个判断,会造成死循环
   if (to.path === '/login') { //这就是跳出循环的关键
      next()
   } else {
       next('/login')
   }
  }
})
  1. 与路由数组里的权限相比较,选出可访问的路由(这里的缺点: 不可随意修改权限,否则需要手动修改vue-router里面的权限列表)
// vuex action
HandleRoute({ commit }, data) { // 处理路由
  return new Promise((resolve, reject) => {
    const roles = data;
    console.log('vuex里面获取route: ', asyncRoutes);
    const accessedRouters = asyncRoutes.filter( item => { // 过滤出可访问的路由
      if(item.meta && item.meta.noShow) return item; // 保留404页面
      if(hasPremission(roles, item)){ // 如果有权限,开始匹配相应的路由
        if(item.children && item.children.length > 0) { //如果路由有子级
          item.children = item.children.filter(child => {
            if(hasPremission(roles, child)) {
              return child;
            }
            return false;
          })
          return item; 
        } else {
          return item;
        }
      }
      return false;
    })
    commit('SET_ROLES', accessedRouters); // 用来渲染侧边栏
    resolve();
  })
}
  1. vue-router里面配置通用路由和权限路由,在router.beforeEach里面利用router.addRoutes挂载权限路由
// route.js
import Vue from 'vue'
import VueRouter, { RouteConfig } from 'vue-router'
import Home from '../views/Home.vue'

Vue.use(VueRouter)

export const commonRoutes = [
  {
    path: '/login',
    name: 'login',
    meta: {title: '登录', noShow: true},
    component: () => import('@/views/login.vue')
  },
  {
    path: '/',
    name: 'home',
    redirect: '/article',
    component: Home,
    children: [
      {
        path: '/article',
        name: 'article',
        meta: {title: '文章'},
        component: () => import('@/views/article.vue')
      },
      {
        path: '/content',
        name: 'content',
        meta: { title: '内容'},
        component: () => import('@/views/content.vue')
      },
    ]
  }
]

export const asyncRoutes = [
  {
    path: '/',
    component: Home,
    redirect: '/article',
    meta: { roles: ['superAdmin', 'admin'] },
    children: [
      {
        path: '/project',
        name: 'project',
        meta: { roles: ['superAdmin', 'admin'], title: '项目'},
        component: () => import('@/views/project.vue')
      }
    ]
  },
  {
    path: '/',
    component: Home,
    redirect: '/article',
    meta: { roles: ['superAdmin'] },
    children: [
      {
        path: '/authority',
        name: 'authority',
        meta: { roles: ['superAdmin'], title: '权限页面' },
        component: () => import('@/views/authority.vue')
      },
    ]
  },
  {
    path: '/',
    component: Home,
    redirect: '/article',
    meta: { roles: ['onlyJing'] },
    children: [
      {
        path: '/private',
        name: 'private',
        meta: { roles: ['onlyJing'], title: '个人页面' },
        component: () => import('@/views/private.vue')
      },
    ]
  },
  {
    path: '*',
    name: 'Error',
    meta: {title: '404', noShow: true},
    component: () => import('@/views/Error.vue')
  }
  
]

const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes: commonRoutes
})

export default router
遇到的坑
1. 怎么显示高亮?

在实现导航高亮的时候,因为使用element中的导航栏,用到了el-menuel-menu-item,这里面只要el-menu中的default-active和el-menu-item中的index保持一致,就可以高亮当前点击的导航,index表示唯一标志,default-active表示当前激活菜单的index,两者皆为string类型。所以这里的index我们可以设为当前循环的路由item.path,而default-active为当前url里面的路由(使用this.route.path来获取。注意:不是this.route.path来获取。注意:不是this.router.path哦~), 同时需要在el-menu里面设置router,router: 是否使用 vue-router 的模式,启用该模式会在激活导航时以 index 作为 path 进行路由跳转

<el-menu 
     :default-active="this.$route.path"
     router
     background-color="#545c64"
     text-color="#fff"
     active-text-color="#ffd04b">
      <el-menu-item v-for="(item, index) in rolesList"
        :key="index"
        :index="item.path">{{ item.meta.title }}</el-menu-item>
    </el-menu>
2. 后台管理系统为什么登陆后刷新还回到登录页以及怎么解决?

因为登录后的token存在vuex里面,而vuex刷新后数据为空,所以在登录请求后,将token存到浏览缓存中,并且在vuex里面state中token的值直接在浏览器缓存中获取,这样每次刷新,token都是有值的,直接走登录后里面的逻辑。

3. 如何做到登录后每次刷新都是在当前路由?

next({ ...to, replace: true }), 一般在router.beforeEach里面动态挂载路由后,使用这个,之所以不使用next()是因为,router.addRoute从解析到挂载到路由,可能会慢于next()的执行,从而next()执行中找不到下一个路由的路径,同时,不使用next('/path')具体跳转到某个路由,就是为了解决每次刷新都是在当前路由的问题,...to是动态记录下一个路由的信息。

4. this.routerthis.router和this.route的区别

this.this.router:表示全局路由对象,项目中通过router路由参数注入路由之后,在任何一个页面都可以通过此方法取到路由对象,并调用其push(), go()等方法
this.this.route: 表示当前正在用于跳转的路由对象,可以调用其name, path, query, params等方法

5. 写 next({ ...to, replace: true })报错 Uncaught(inpromise)Error:Redirectedwhengoingfrom"/login"to"/article"viaanavigationguard.\color{red}{Uncaught (in promise) Error: Redirected when going from "/login" to "/article" via a navigation guard.} 解决方法?

目前想到的办法就是,将vue-router的版本回退到低一些的版本,比如3.0.7版本,具体原因不详

6. 如果是http://localhost:8080/#/怎么重定向到默认路由页面?登录后手动输入url怎么重定向到404页面?
  • 在路由里面设置redirect: '/article',重定向到默认页面
  • 在路由router.js里面,利用通配符,将不匹配的路由全部重定向到404页面,同时,将404路由在权限路由中写,因为要保证该路由要在路由数组的最后, 同时在action里面筛选动态路由的时候,主要不要过滤了该路由,由此,这里加了个参数noShow作为标识
{
  path: '*',
  name: 'Error',
  meta: {title: '404', noShow: true},
  component: () => import('@/views/Error.vue')
}
7. 怎么退出登录
loginOut() {
   delCookie('token'); // 清除cookie
   window.location.reload(); // 刷新页面
}