vue实现路由守卫
路由守卫的基本概念
路由守卫是 Vue Router 提供的一种机制,用于在路由跳转前后执行特定的逻辑。通过路由守卫,可以实现权限控制、页面访问限制、数据预加载等功能。
全局前置守卫
使用 router.beforeEach 注册全局前置守卫,在路由跳转前执行逻辑。常用于权限验证或登录状态检查。
router.beforeEach((to, from, next) => {
const isAuthenticated = checkAuth(); // 假设的认证检查函数
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login');
} else {
next();
}
});
全局解析守卫
router.beforeResolve 在导航被确认之前触发,适合用于获取数据或执行其他异步操作。
router.beforeResolve(async (to, from, next) => {
try {
await fetchDataBeforeEnter(to.params.id);
next();
} catch (error) {
next('/error');
}
});
全局后置钩子
router.afterEach 在导航完成后触发,适合用于页面统计或日志记录。

router.afterEach((to, from) => {
logPageView(to.path);
});
路由独享守卫
在路由配置中直接定义 beforeEnter 守卫,仅对该路由生效。
const routes = [
{
path: '/profile',
component: Profile,
beforeEnter: (to, from, next) => {
if (!isUserLoggedIn()) {
next('/login');
} else {
next();
}
}
}
];
组件内守卫
在组件内部定义守卫,包括 beforeRouteEnter、beforeRouteUpdate 和 beforeRouteLeave。

export default {
beforeRouteEnter(to, from, next) {
// 在渲染该组件的对应路由被确认前调用
next(vm => {
// 通过 `vm` 访问组件实例
});
},
beforeRouteUpdate(to, from, next) {
// 当前路由改变但该组件被复用时调用
next();
},
beforeRouteLeave(to, from, next) {
// 导航离开该组件的对应路由时调用
if (confirm('确定要离开吗?')) {
next();
} else {
next(false);
}
}
};
动态路由守卫
结合 Vuex 或其他状态管理工具,实现动态权限控制。
router.beforeEach((to, from, next) => {
const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
const currentUser = store.state.user;
if (requiresAuth && !currentUser) {
next('/login');
} else if (to.path === '/login' && currentUser) {
next('/');
} else {
next();
}
});
路由元信息
利用 meta 字段存储路由的额外信息,便于在守卫中进行判断。
const routes = [
{
path: '/admin',
component: Admin,
meta: { requiresAuth: true, roles: ['admin'] }
}
];
异步路由守卫
在守卫中处理异步操作时,确保正确调用 next。
router.beforeEach(async (to, from, next) => {
try {
const user = await fetchUser();
if (user) {
next();
} else {
next('/login');
}
} catch (error) {
next('/error');
}
});
通过以上方法,可以灵活地实现各种路由控制需求,确保应用的安全性和用户体验。






