Loading

后台系统的权限管理

背景

后台管理系统可以有不同的角色进行登录,我们希望对不同角色进行页面访问控制。
比如:

  • 用户a为普通用户,只能访问home路由、访问其他路由的话则显示not-found
  • 用户b为管理员,可以访问所有的路由

实现

环境

"vue": "^2.6.14",
"vue-router": "^3.5.1",
"vuex": "^3.6.2"

具体代码:

  1. 静态路由注册,然后挂载到vue实例上
// router/index.js
import Home from "@/components/Home.vue";
import NotFound from "@/components/NotFound.vue";

const routes = [
  { path: "/home", component: Home },
  { path: "*", component: NotFound },
];
  1. 路由前置守卫监听访问的页面是否是需要权限的页面、是否有登录,有登录过直接放行,没有登录过则获取用户信息并动态注册路由
// main.js
router.beforeEach((to, from, next) => {
  if (to.path != "/login") {
    if (!store.state.isLogin) {
      store.dispatch("getUserInfoAction").then((res) => {
        if (res) {
          next(to.path);
        }
      });
    } else {
      next();
    }
  } else {
    next();
  }
});

// store/index.js
export default new Vuex.Store({
  state: {
    // 1. 记录用户是否登录
    isLogin: false,
    // 2. 记录用户信息
    userInfo: {},
  },
  getters: {},
  mutations: {
    changeUserInfo(state, playload) {
      state.isLogin = true;
      state.userInfo = playload;
    },
  },
  actions: {
    // 3. 获取用户信息
    async getUserInfoAction({ commit }) {
      const userInfo = await axios.get("/get_user_info");
      if (!userInfo) {
        return false;
      }
      commit("changeUserInfo", userInfo);

      const routes = [];
      // 针对不同角色的路由进行动态注册
      if (userInfo.role == "管理员") {
        routes.push(...dynamicRoutes);
      }
      routes.forEach((route) => {
        router.addRoute(route);
      });
      console.log(router.getRoutes());
      return true;
    },
  },
  modules: {},
});

// dynamicRoutes.js
import About from "@/components/About.vue";
import AboutHaHa from "@/components/AboutHaHa.vue";

const dynamicRoutes = [
  { path: "/order", component: Order },
  {
    path: "/about",
    component: About,
    children: [
      {
        path: "haha",
        component: AboutHaHa,
      },
    ],
  },
];
export default dynamicRoutes;

效果

普通用户

管理员

posted @ 2022-10-24 23:06  ^Mao^  阅读(207)  评论(0编辑  收藏  举报