面试题:Vue Router 的导航守卫有哪些?它们接受哪些参数?

Vue Router 的导航守卫(Navigation Guards)是用于控制路由跳转的钩子函数。

它们允许你在路由跳转的不同阶段执行逻辑,例如权限校验、数据预加载等。

Vue Router 提供了三种类型的导航守卫:


1. 全局导航守卫

全局导航守卫作用于所有路由,包括以下三种:

1.1 router.beforeEach

  • 作用:在路由跳转之前执行。
  • 参数
    • to:目标路由对象(即将进入的路由)。
    • from:当前路由对象(即将离开的路由)。
    • next:回调函数,用于控制路由跳转。
      • next():继续路由跳转。
      • next(false):中断当前导航。
      • next('/path'):跳转到指定路径。
      • next(error):传入一个 Error 实例,取消导航并触发错误。
  • 示例
router.beforeEach((to, from, next) => {
const isAuthenticated = checkAuth(); // 检查用户是否登录
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login'); // 跳转到登录页
} else {
next(); // 继续导航
}
});
  router.beforeEach((to, from, next) => {
    const isAuthenticated = checkAuth(); // 检查用户是否登录
    if (to.meta.requiresAuth && !isAuthenticated) {
      next('/login'); // 跳转到登录页
    } else {
      next(); // 继续导航
    }
  });
router.beforeEach((to, from, next) => { const isAuthenticated = checkAuth(); // 检查用户是否登录 if (to.meta.requiresAuth && !isAuthenticated) { next('/login'); // 跳转到登录页 } else { next(); // 继续导航 } });

1.2 router.beforeResolve

  • 作用:在导航被确认之前执行(在所有组件内守卫和异步路由组件解析之后)。
  • 参数:与 beforeEach 相同。
  • 示例
router.beforeResolve((to, from, next) => {
// 在导航确认前执行逻辑
next();
});
  router.beforeResolve((to, from, next) => {
    // 在导航确认前执行逻辑
    next();
  });
router.beforeResolve((to, from, next) => { // 在导航确认前执行逻辑 next(); });

1.3 router.afterEach

  • 作用:在导航完成后执行(没有 next 参数,不能改变导航)。
  • 参数
    • to:目标路由对象。
    • from:当前路由对象。
  • 示例
router.afterEach((to, from) => {
console.log('导航完成');
});
  router.afterEach((to, from) => {
    console.log('导航完成');
  });
router.afterEach((to, from) => { console.log('导航完成'); });

2. 路由独享的守卫

路由独享的守卫定义在路由配置中,只对当前路由生效。

2.1 beforeEnter

  • 作用:在进入特定路由之前执行。
  • 参数:与 beforeEach 相同。
  • 示例
const routes = [
{
path: '/admin',
component: Admin,
beforeEnter: (to, from, next) => {
const isAdmin = checkAdmin(); // 检查用户是否是管理员
if (isAdmin) {
next(); // 继续导航
} else {
next('/'); // 跳转到首页
}
},
},
];
  const routes = [
    {
      path: '/admin',
      component: Admin,
      beforeEnter: (to, from, next) => {
        const isAdmin = checkAdmin(); // 检查用户是否是管理员
        if (isAdmin) {
          next(); // 继续导航
        } else {
          next('/'); // 跳转到首页
        }
      },
    },
  ];
const routes = [ { path: '/admin', component: Admin, beforeEnter: (to, from, next) => { const isAdmin = checkAdmin(); // 检查用户是否是管理员 if (isAdmin) { next(); // 继续导航 } else { next('/'); // 跳转到首页 } }, }, ];

3. 组件内的守卫

组件内的守卫定义在 Vue 组件中,只对当前组件生效。

3.1 beforeRouteEnter

  • 作用:在进入组件之前执行(此时组件实例尚未创建)。
  • 参数
    • to:目标路由对象。
    • from:当前路由对象。
    • next:回调函数。
      • next(vm => { ... }):可以通过 vm 访问组件实例。
  • 示例
export default {
beforeRouteEnter(to, from, next) {
next((vm) => {
console.log('组件实例:', vm);
});
},
};
  export default {
    beforeRouteEnter(to, from, next) {
      next((vm) => {
        console.log('组件实例:', vm);
      });
    },
  };
export default { beforeRouteEnter(to, from, next) { next((vm) => { console.log('组件实例:', vm); }); }, };

3.2 beforeRouteUpdate

  • 作用:在当前路由改变但组件复用时执行(例如,动态路由参数变化时)。
  • 参数:与 beforeRouteEnter 相同。
  • 示例
export default {
beforeRouteUpdate(to, from, next) {
console.log('路由参数变化');
next();
},
};
  export default {
    beforeRouteUpdate(to, from, next) {
      console.log('路由参数变化');
      next();
    },
  };
export default { beforeRouteUpdate(to, from, next) { console.log('路由参数变化'); next(); }, };

3.3 beforeRouteLeave

  • 作用:在离开组件之前执行。
  • 参数:与 beforeRouteEnter 相同。
  • 示例
export default {
beforeRouteLeave(to, from, next) {
const confirmLeave = confirm('确定要离开吗?');
if (confirmLeave) {
next(); // 继续导航
} else {
next(false); // 中断导航
}
},
};
  export default {
    beforeRouteLeave(to, from, next) {
      const confirmLeave = confirm('确定要离开吗?');
      if (confirmLeave) {
        next(); // 继续导航
      } else {
        next(false); // 中断导航
      }
    },
  };
export default { beforeRouteLeave(to, from, next) { const confirmLeave = confirm('确定要离开吗?'); if (confirmLeave) { next(); // 继续导航 } else { next(false); // 中断导航 } }, };

4. 导航守卫的执行顺序

导航守卫的执行顺序如下:

  1. 全局守卫
    • beforeEach
  2. 路由独享守卫
    • beforeEnter
  3. 组件内守卫
    • beforeRouteEnter
    • beforeRouteUpdate
  4. 全局解析守卫
    • beforeResolve
  5. 全局后置钩子
    • afterEach

5. 总结

Vue Router 的导航守卫包括:

  1. 全局守卫
    • beforeEach:路由跳转前执行。
    • beforeResolve:导航确认前执行。
    • afterEach:导航完成后执行。
  2. 路由独享守卫
    • beforeEnter:进入特定路由前执行。
  3. 组件内守卫
    • beforeRouteEnter:进入组件前执行。
    • beforeRouteUpdate:路由参数变化时执行。
    • beforeRouteLeave:离开组件前执行。

通过合理使用导航守卫,可以实现权限控制、数据预加载、页面拦截等功能,提升应用的用户体验和安全性。

THE END
点赞5 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容