javaScript单页应用路由核心是利用history API(pushState/replaceState/popstate)或hash模式实现URL变更不刷新页面,通过监听URL变化匹配路由表并动态渲染视图,主流框架如react router、vue Router均基于此原理封装。

javascript 单页面应用(SPA)的路由机制,核心是不刷新页面的前提下改变 URL 并响应视图切换。它不依赖服务端返回新 html,而是靠前端监听 URL 变化、匹配路径、动态渲染对应组件或内容。
URL 改变不触发页面刷新的关键:History API
现代 SPA 路由基于浏览器原生的 History API(pushState、replaceState 和 popstate 事件),而非早期的 hash(#)方式。
-
history.pushState(state, title, url):向历史栈添加一条记录,更新地址栏 URL(可为任意同源路径),但不请求服务器、不刷新页面 -
history.replaceState():替换当前历史记录,URL 变更但不新增历史项 - 用户点击「后退」「前进」或调用
history.back()时,会触发popstate事件,js 可捕获并重新渲染视图
路由匹配与视图渲染:手动实现一个极简路由
无需框架也能理解原理。下面是一个基于 History API 的简易路由示例:
// 定义路由表 const routes = { '/': () => renderHome(), '/about': () => renderAbout(), '/user/:id': (params) => renderUser(params.id) }; // 解析 URL 参数(简化版) function parsePath(path) { const match = path.match(/^/user/(d+)$/); return match ? { id: match[1] } : null; } // 渲染函数(模拟) function renderHome() { document.body.innerHTML = '首页
'; } function renderAbout() { document.body.innerHTML = '关于页
'; } function renderUser(id) { document.body.innerHTML = `用户 ${id}
`; } // 响应路由变化 function route() { const path = window.location.pathname; if (routes[path]) { routes[path](); } else if (path.startsWith('/user/')) { const params = parsePath(path); if (params) routes['/user/:id'](params); } } // 初始化 + 监听 window.addEventListener('popstate', route); route(); // 首次加载时执行 // 导航函数(替代 ) function goTo(path) { history.pushState({}, '', path); route(); }
Hash 模式:兼容性更强的备选方案
在不支持 History API 的旧环境(或需服务端免配置部署时),可用 hash 模式:
立即学习“Java免费学习笔记(深入)”;
- URL 形如
https://example.com/#/about,location.hash变化不会导致页面刷新 - 监听
hashchange事件代替popstate - 修改 hash:用
location.hash = '/about' - 缺点:URL 不够美观,seo 友好性略差(现代搜索引擎已能处理,但仍非首选)
实际开发中如何用?
主流框架封装了成熟路由库:
- React:使用 React Router(v6 推荐
+useNavigate+useParams) - Vue:使用 Vue Router(
createRouter({ history: createWebHistory() })) - angular:内置 RouterModule,默认基于 History API
它们自动处理路由注册、嵌套路由、懒加载、守卫(导航守卫)、滚动行为等,但底层仍依赖上述 History 或 Hash 机制。