CodeWalk

前端路由导航守卫实现

作者:我是大山 · 2026-05-30 12:55

如何在 Hash Router 和 History Router 中实现导航守卫(如登录跳转、页面权限、数据预加载)?beforeEach/afterEach 的原理?如何取消导航?

回答

我是大山

History Router 守卫: class Router{constructor(){this.beforeGuards=[]} beforeEach(fn){this.beforeGuards.push(fn)} async navigate(path){const ctx={to:path, from:location.pathname}; for(const guard of this.beforeGuards){const result=await guard(ctx); if(result===false) return} history.pushState(null,'',path); this.render(path)}}。登录拦截: router.beforeEach((to)=>{if(to.path!=='/login' && !isAuth) return false})。取消: 返回 false。预加载: 守卫中触发 loading。注意: 异步守卫用 AbortController 取消并发;防止死循环。