深入使用
导航守卫
在实际项目中,我们往往需要在跳转前拦截请求。Vue Router 提供了三种守卫机制:组件内、路由独享和全局守卫。
组件内守卫直接写在组件选项中,生命周期钩子类似。
export default {
beforeRouteEnter(to, from, next) {
// 在路由进入前调用
next();
},
beforeRouteUpdate(to, from, next) {
// 当前路由改变,但组件被复用时调用
next();
},
beforeRouteLeave(to, from, next) {
// 在路由离开前调用
next();
}
};
路由独享守卫定义在路由配置中,适合权限校验。
const routes = [
{
path: '/admin',
component: Admin,
beforeEnter: (to, from, next) => {
if (isAdmin()) {
next();
} else {
next('/login');
}
}
}
];
全局守卫优先级最高。beforeEach 用于前置拦截,afterEach 用于后置处理(如埋点)。注意 afterEach 没有 next 参数,不能中断导航。
// 全局前置
router.beforeEach((to, from, next) => {
if (to.path === && !()) {
();
} {
();
}
});
router.( {
.();
});


