CodeWalk

SPA 前端路由原理:History Router

作者:编译有声 · 2026-05-30 12:55

HTML5 History API 如何实现前端路由?pushState/replaceState 和 popstate 事件的配合使用?与 Hash Router 相比优劣如何?需要怎样的服务端配合?

回答

编译有声

history.pushState(state, title, url) 改变 URL 不刷新;popstate 监听前进/后退。实现: 点击链接 e.preventDefault()+pushState+renderRoute;popstate 中 renderRoute(location.pathname)。优点: URL 美观、SEO 友好。缺点: 需服务端配置——所有路径返回 index.html。Nginx: try_files $uri $uri/ /index.html。注意: pushState 不触发 popstate,需手动渲染;popstate 中需从 location 获取路径。可与 Hash 混用 fallback。