前端路由核心是监听URL变化、解析路径、匹配规则并动态渲染,关键用history.pushState、popstate事件和路径解析逻辑,需手动触发首次匹配并处理404与服务端配置。
用 JavaScript 实现前端路由,核心是监听 URL 变化、解析路径、匹配规则、动态渲染对应内容——不依赖框架也能做到,关键是掌握 history.pushState、popstate 事件和 URL 解析逻辑。
单页应用(SPA)不能靠刷新跳转,得用 History API 操作路由状态:
history.pushState(state, title, url) 替换当前 URL(不触发刷新),比如 pushState(null, '', '/about')
window.addEventListener('popstate', handler) 捕获后退/前进操作popstate 不会触发页面初始加载)把 URL 路径(location.pathname)和预定义的路由表比对,支持静态路径和简单参数:
if (path === '/home') renderHome()
或 URLPattern(较新,兼容性注意)提取,例如 /user/:id → 匹配 /user/123,取到 id = '123'
{ '/': homeHandler, '/post/:id': postHandler },遍历时用 path.startsWith 或正则测试封装成类更易复用,内部管理路由表、监听、跳转方法:
class SimpleRouter { constructor(routes) { this.routes = routes; this.init(); } init() { window.addEventListener('popstate', () => this.route()); this.route(); // 首次加载 } route() { const path = location.pathname; const match = Object.keys(this.routes).find(key => { const regex = ^${key.replace(/:(\w+)/g, '([^/]+)')}$; return regex.test(path); }); if (match) { const args = path.match(new RegExp(^${match.replace(/:(\w+)/g, '([^/]+)')}$)); this.routes[match](args?.slice(1) || []); } else { this.routes['*']?.(); } } go(path) { history.pushState(null, '', path); this.route(); } }使用:
new SimpleRouter({ '/': renderHome, '/user/:id': ([id]) => renderUser(id) })处理锚点与 404
真实项目中要兼顾边界情况:
- 忽略 hash(如
#section1):只取location.pathname,别用location.href- 未匹配路径:加一个
'*'通配符路由,显示 404 页面- 服务端配合:部署时确保所有路由都返回 index.html(否则直接访问 /admin 会 404)
基本上就这些。不复杂但容易忽略首次加载和 history 状态管理——写完记得测一下点击链接、浏览器前后按钮、直接输入 URL 这三种场景是否都正常。