
 在Vue中,防止未授权用户访问受保护页面通常涉及到使用路由守卫(Route Guards)。路由守卫允许你在路由发生改变前或后执行一些逻辑,比如检查用户是否已登录或者有访问某个页面的权限。下面是一些常见的路由守卫类型及其使用方式:
1. 全局前置守卫(Global Before Guards)
beforeEach 守卫会在每次路由转换前调用,你可以在这里检查用户的登录状态和权限。
const router = new VueRouter({
  routes: [...]
});
router.beforeEach((to, from, next) => {
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
  
  if (requiresAuth && !auth.isLoggedIn()) {
    // 如果页面需要认证并且用户没有登录,则重定向到登录页面
    next({ path: '/login' });
  } else {
    next();
  }
});
 
2. 路由级守卫(Route-Level Guards)
在路由配置中,你可以直接在路由对象上添加守卫,这使得某些路由具有更细粒度的控制。
const routes = [
  {
    path: '/protected',
    name: 'ProtectedPage',
    component: ProtectedPage,
    meta: { requiresAuth: true },
    beforeEnter: (to, from, next) => {
      if (!auth.isLoggedIn()) {
        return next('/login');
      }
      next();
    }
  },
  // ...
];
 
3. 组件内的守卫(Component Guards)
你还可以在组件内部使用守卫,比如 beforeRouteEnter 和 beforeRouteUpdate。
export default {
  // ...
  beforeRouteEnter(to, from, next) {
    if (!auth.isLoggedIn()) {
      next('/login');
    } else {
      next();
    }
  },
  // ...
};
 
4. 使用 Vuex Store
结合 Vuex,你可以更方便地在全局范围内管理用户的登录状态和权限信息。在登录时,将权限信息存储在 Vuex store 中,然后在路由守卫中读取这些信息。
// store.js
const store = new Vuex.Store({
  state: {
    isLoggedIn: false,
    userPermissions: []
  },
  mutations: {
    SET_LOGIN_STATUS(state, status) {
      state.isLoggedIn = status;
    },
    SET_PERMISSIONS(state, permissions) {
      state.userPermissions = permissions;
    }
  },
  // ...
});
 
然后在路由守卫中检查 store.state.isLoggedIn 和 store.state.userPermissions。
实现细节
- 权限检查:确保你的守卫逻辑能够正确检查用户权限,例如,对于管理员级别的页面,检查用户是否具有管理员权限。
 - 重定向:如果用户没有必要的权限,通常会重定向到登录页面或一个友好的错误页面。
 - 错误处理:考虑加入错误处理机制,比如网络请求失败时的处理。
 



















