vue-element-admin 使用总结

官网https://panjiachen.github.io/vue-element-admin-site/zh/guide/#%E5%8A%9F%E8%83%BD

vue项目做的少,elementUI也是最近才接触,所以文档看了一周才有了点思路,最难的就是用户登录权限部分

目录结构

页面都在/src/views 下

登录权限

登录在src/views/login/index.vue ,登录只是账号密码,登录后获取用户信息其中包含用户角色,路由配置在src/router/index.js,路由中配置了每个路由对应的角色

侧边栏动态渲染

src/router/index.js 路由配置里有公共的路由constantRoutes和异步路由asyncRoutes,异步路由是根据在 meta里设置roles来实现动态的meta: { title: 'permission', icon: 'lock', roles: ['admin', 'editor']},

权限的判断 是在 src/store/modules/permission.js文件里,有个actions。判断如果角色里包含admin(一个用户可多个角色,所以返回的角色是个数组),就显示全部的,否则的话需要做判断,还是根据 route.meta.roles.includes(role) 来判断路由是否包含返回的角色

GenerateRoutes({ commit }, data) {
  return new Promise(resolve => {
    const { roles } = data
    let accessedRoutes
    if (roles.includes('admin')) {
      accessedRoutes = asyncRoutes
    } else {
      accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
    }
    commit('SET_ROUTES', accessedRoutes)
    resolve(accessedRoutes)
  })
}

动态加载路由肯定要在全局做判断,需要写在路由跳转之前router.beforeEach,根据目录结构可以知道是在src/permission.js中, store.dispatch('GenerateRoutes') 通过调用vuex中的方法获得路由权限,没有权限的话就跳401

 1 router.beforeEach((to, from, next) => {
 2   if (store.getters.token) { // 判断是否有token
 3     if (to.path === '/login') {
 4       next({ path: '/' });
 5     } else {
 6       if (store.getters.roles.length === 0) { // 判断当前用户是否已拉取完user_info信息
 7         store.dispatch('GetInfo').then(res => { // 拉取info
 8           const roles = res.data.role;
 9           store.dispatch('GenerateRoutes', { roles }).then(() => { // 生成可访问的路由表
10             router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
11             next({ ...to, replace: true }) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
12           })
13         }).catch(err => {
14           console.log(err);
15         });
16       } else {
17         next() //当有用户权限的时候,说明所有可访问路由已生成 如访问没权限的全面会自动进入404页面
18       }
19     }
20   } else {
21     if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单,直接进入
22       next();
23     } else {
24       next('/login'); // 否则全部重定向到登录页
25     }
26   }
27 });

后台权限配置

3月15号刚更新的后台可以进行权限配置了,先看下界面

也就是说 

猜你喜欢

转载自www.cnblogs.com/shuran/p/10616824.html