推荐答案
在 Vue Router 中,导航守卫(Navigation Guards)主要分为以下几类:
- 全局前置守卫:
router.beforeEach - 全局解析守卫:
router.beforeResolve - 全局后置钩子:
router.afterEach - 路由独享的守卫:
beforeEnter - 组件内的守卫:
beforeRouteEnterbeforeRouteUpdatebeforeRouteLeave
本题详细解读
1. 全局前置守卫 (router.beforeEach)
全局前置守卫在路由跳转之前执行,可以用来进行权限验证、登录状态检查等操作。它接收三个参数:
to:即将进入的目标路由对象。from:当前导航正要离开的路由对象。next:一个函数,必须调用next()来 resolve 这个钩子。
router.beforeEach((to, from, next) => {
// 权限验证逻辑
if (to.meta.requiresAuth && !isAuthenticated()) {
next('/login');
} else {
next();
}
});2. 全局解析守卫 (router.beforeResolve)
全局解析守卫在导航被确认之前,同时在所有组件内守卫和异步路由组件被解析之后调用。它和 beforeEach 类似,但确保所有的异步组件都已经解析完成。
router.beforeResolve((to, from, next) => {
// 确保所有异步组件都已解析
next();
});3. 全局后置钩子 (router.afterEach)
全局后置钩子在导航完成后执行,不会接收 next 函数,也不会改变导航本身。通常用于日志记录、页面统计等操作。
router.afterEach((to, from) => {
// 记录页面访问日志
logPageView(to.path);
});4. 路由独享的守卫 (beforeEnter)
路由独享的守卫可以直接在路由配置上定义 beforeEnter 守卫,它只在进入该路由时触发。
// www.javascriptcn.com code example
const routes = [
{
path: '/dashboard',
component: Dashboard,
beforeEnter: (to, from, next) => {
// 路由独享的守卫逻辑
if (isAuthenticated()) {
next();
} else {
next('/login');
}
}
}
];5. 组件内的守卫
组件内的守卫允许你在组件内部定义导航守卫,主要有以下三种:
beforeRouteEnter:在进入该组件之前调用,此时组件实例还未创建,因此无法访问this。beforeRouteUpdate:在当前路由改变,但该组件被复用时调用。beforeRouteLeave:在离开该组件时调用。
// www.javascriptcn.com code example
export default {
beforeRouteEnter(to, from, next) {
// 组件实例还未创建
next(vm => {
// 通过 `vm` 访问组件实例
});
},
beforeRouteUpdate(to, from, next) {
// 当前路由改变,但组件被复用时调用
next();
},
beforeRouteLeave(to, from, next) {
// 离开该组件时调用
if (confirm('确定要离开吗?')) {
next();
} else {
next(false);
}
}
};