Vue 路由守卫

发布于:2025-03-20 ⋅ 阅读:(29) ⋅ 点赞:(0)


一、全局路由守卫 router.js

1. 前置守卫

router.beforeEach((to, from, next) => {
  // to: Route 即将要进入的目标 路由对象
  // from: Route 当前导航正要离开的路由
  // next: Function 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。
 
  // 例如,验证用户是否已登录
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!auth.isLoggedIn()) {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      });
    } else {
      next();
    }
  } else {
    next(); // 确保一定要调用 next()
  }
});

2. 后置钩子

router.afterEach((to, from) => {
  // to: Route 即将要进入的目标 路由对象
  // from: Route 当前导航正要离开的路由对象
  // 全局后置钩子,不会接受 next 函数也不会改变导航本身
  if (to.meta.title) {
    document.title = to.meta.title + " - 系统名称"
  }
  console.log('Navigation completed successfully.');
});

二、路由独享的守卫

const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      beforeEnter: (to, from, next) => {
        // 参数和全局前置守卫类似
      }
    }
  ]
});

三、组件内的守卫

可以在路由组件内直接定义以下三个路由守卫:

beforeRouteEnter
beforeRouteUpdate (2.2+ 支持)
beforeRouteLeave

示例:beforeRouteEnter 守卫

export default {
  name: 'UserProfile',
  beforeRouteEnter(to, from, next) {
    // 在渲染该组件的对应路由被 confirm 前调用
    // 不能获取组件实例 `this` 组件实例尚未创建
    next(vm => {
      // 通过 `vm` 访问组件实例
    });
  },
  beforeRouteLeave(to, from, next) {
    // 导航离开该组件的对应路由时调用
    // 可以访问组件实例 `this`
    const answer = window.confirm('Do you really want to leave? you have unsaved changes!');
    if (answer) {
      next(); // 确保调用 next() 方法,否则钩子就不会被 resolved。
    } else {
      next(false); // 使用 'next(false)' 来取消导航并停留在当前页面。或者可以使用 'next('/')' 或者 'next(new Location)' 来跳转到不同的地址。
    }
  }
}