vue路由拦截怎么实现
Vue 路由拦截的实现方法
Vue 路由拦截通常通过 Vue Router 的导航守卫(Navigation Guards)实现,主要用于权限控制、登录验证等场景。以下是几种常见的实现方式:
全局前置守卫
使用 router.beforeEach 可以在路由跳转前进行拦截。该方法接收三个参数:to(目标路由)、from(当前路由)和 next(回调函数)。
router.beforeEach((to, from, next) => {
const isAuthenticated = checkAuth(); // 检查用户是否登录
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login'); // 跳转到登录页
} else {
next(); // 允许跳转
}
});
路由独享守卫
在路由配置中直接定义 beforeEnter 守卫,仅对当前路由生效。
const routes = [
{
path: '/dashboard',
component: Dashboard,
beforeEnter: (to, from, next) => {
if (!checkAuth()) {
next('/login');
} else {
next();
}
}
}
];
组件内守卫
在 Vue 组件中通过 beforeRouteEnter、beforeRouteUpdate 或 beforeRouteLeave 实现拦截。
export default {
beforeRouteEnter(to, from, next) {
// 在渲染该组件的对应路由被验证前调用
next(vm => {
// 通过 `vm` 访问组件实例
});
},
beforeRouteLeave(to, from, next) {
// 在离开路由前调用
if (confirm('确定离开吗?')) {
next();
} else {
next(false); // 取消导航
}
}
};
全局后置钩子
通过 router.afterEach 在路由跳转完成后执行逻辑,适合用于日志记录或页面标题更新。
router.afterEach((to, from) => {
document.title = to.meta.title || '默认标题';
});
注意事项
- 确保调用
next(),否则路由会卡住。 - 路由元信息(
meta字段)可用于标记权限需求。 - 异步操作(如 API 请求)需在
next调用前完成。







