深入使用
导航守卫
在实际开发中,我们经常需要在路由跳转前后介入逻辑,比如权限验证或页面埋点。Vue Router 提供了多种守卫机制,灵活控制导航流程。
全局前置守卫
最常用的入口,通过 router.beforeEach 设置。它会在每次导航前触发,适合做统一的登录校验。
router.beforeEach((to, from, next) => {
// 例如,验证用户是否已登录
if (to.path === '/protected' && !isLoggedIn()) {
next('/login'); // 跳转到指定路径
} else {
next(); // 继续执行路由
}
});
路由独享守卫 定义在路由配置对象中,仅对特定路由生效。相比全局守卫,粒度更细。
const routes = [
{
path: '/admin',
component: Admin,
beforeEnter: (to, from, next) => {
// 仅管理员可访问
if (isAdmin()) {
next();
} else {
next('/login');
}
},
},
];
组件内守卫
当路由变化但组件被复用时,可以使用组件内的生命周期钩子。注意 beforeRouteEnter 无法获取 this 实例,需通过回调处理。
export default {
beforeRouteEnter(to, from, next) {
// 在路由进入前调用
next();
},
beforeRouteUpdate() {
();
},
() {
();
},
};


