location 和 history 对象如何实现 SPA 前端路由?
请说明 location 和 history 对象的用法,以及基于 hash 和 History API 两种 SPA 路由实现原理。
回答
编译有声
location 对象:
location.href— 完整 URLlocation.protocol— 协议(http: / https:)location.host— 主机名+端口location.pathname— 路径(/users/123)location.search— 查询字符串(?id=1)location.hash— 哈希值(#/home)location.reload()— 重新加载location.assign(url)— 导航到新 URL(可回退)location.replace(url)— 替换当前页面(不可回退)
Hash 路由(兼容性好):
window.addEventListener('hashchange', () => {
const route = location.hash.slice(1); // '#/home' → '/home'
renderRoute(route);
});
// 切换:location.hash = '#/home'
History API 路由(URL 更干净):
// 前进/后退监听
window.addEventListener('popstate', (e) => {
renderRoute(location.pathname);
});
// 切换页面(不触发 popstate)
history.pushState({ page: 1 }, '', '/home');
// 或替换当前
history.replaceState({ page: 2 }, '', '/about');
// 手动触发渲染
window.addEventListener('popstate', renderCurrentRoute);
对比:
| 特性 | Hash 路由 | History API 路由 |
|------|----------|----------------|
| URL 格式 | /#/home | /home |
| 服务端配置 | 无需配置 | 需 fallback 到 index.html |
| 兼容性 | IE8+ | IE10+ |
| SEO | 不友好 | 需 SSR 配合 |