Vue Router 中实现 beforeEach

要在 Vue Router 的 beforeEach 导航守卫中实现基于角色的访问控制,你需要先确定用户的角色,并根据该角色检查他们是否有权访问目标路由。假设你有一个地方可以获取当前用户的角色(例如,存储在 Vuex 状态管理中或通过一个 API 调用获取),你可以使用这些信息来动态地控制访问。
以下是一个修改后的 beforeEach 守卫示例,它实现了这个逻辑:

import Vue from 'vue';
import Router from 'vue-router';
import Dashboard from './views/Dashboard';
import store from './store'; // 假设你有一个 Vuex store

Vue.use(Router);

let router = new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('./views/Login'),
    },
    {
      path: '/404',
      name: '404',
      component: () => import('./views/dashboard/404'),
    },
    {
      path: '/dashboard',
      component: Dashboard,
      meta: { requiresAuth: true },
      children: [
        {
          path: 'home_list',
          name: 'homeList',
          component: () => import('./views/dashboard/HomeList'),
          props: true,
          meta: { type: [0, 1] },
        },
        {
          path: 'wal_config',
          name: 'walConfig',
          component: () => import('./views/dashboard/WalletConfig'),
          props: true,
          meta: { type: [0, 1, 5, 7] },
        },
        {
          path: 'wal_configEn',
          name: 'walConfigEn',
          component: () => import('./views/dashboard/WalletConfigEn'),
          props: true,
          meta: { type: [] },
        },
      ],
    },
  ],
});

// 假设获取用户角色的函数
function getUserRole() {
  // 从 Vuex store 或其他地方获取当前用户角色
  return store.state.user.role;
}

router.beforeEach((to, from, next) => {
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
  const userRole = getUserRole();

  if (requiresAuth) {
    if (to.meta.type && !to.meta.type.includes(userRole)) {
      // 如果路由需要特定角色,并且当前用户角色不在允许的列表中
      next({ name: '404' });
    } else {
      // 用户有权限访问该路由
      next();
    }
  } else {
    // 路由不需要认证,直接放行
    next();
  }
});

export default router;

在这个示例中,getUserRole 函数应该返回当前用户的角色。这个函数可以从 Vuex store 或其他你存储用户信息的地方获取角色数据。

在 beforeEach 守卫中,首先检查路由是否需要认证(requiresAuth)。如果需要,再检查目标路由的 meta.type 是否包含当前用户的角色。如果不包含,就重定向到 404 页面;否则,允许访问。

确保你已经在 Vuex store 或其他适当的地方设置了用户角色,并且 getUserRole 函数能正确返回这个角色。

posted @ 2025-02-12 11:07  维维WW  阅读(186)  评论(0)    收藏  举报