面试题库 词条目录
前端Wiki/词条/前端路由原理

前端路由原理

定义SPA 不刷新页面切换视图的原理:hash 路由与 history 路由两种实现

hash 路由:URL 中 # 后面的部分变化(# 之后不发请求给服务器,本来就不会刷新),监听 hashchange 事件切换组件。兼容性最好、不需要服务器配合;缺点是 SEO 不友好、URL 带 # 号。

history 路由:用 History API 的 pushState/replaceState 改 URL,配合 popstate 事件切换。URL 干净(/user/42),但刷新时浏览器会真的去请求 /user/42 —— 服务器必须配置「所有路径一律返回 index.html」否则 404。现代方案基本都选 history + 服务器回退配置。

JavaScript
// 手写一个最简路由:两版实现同一个功能

// ---- 版本 A:hash 路由 ----
window.addEventListener('hashchange', () => {
  const path = location.hash.slice(1) || '/';
  render(path);                      // 切换视图
});
location.hash = '/user';             // 改 URL(不刷新页面)

// ---- 版本 B:history 路由 ----
function go(path) {
  history.pushState({ path }, '', path);   // ★ 改 URL 不触发任何事件
  render(path);                            // 需要自己调用渲染
}
window.addEventListener('popstate', e => { // 前进/后退才触发
  render(e.state.path || '/');
});

// ─────────── 服务器配置(history 模式必需) ───────────
// Nginx:
//   location / {
//     try_files $uri $uri/ /index.html;   # 找不到就回退到 index.html
//   }
// Express:
//   app.get('*', (req, res) => res.sendFile('index.html'));
⚠ 常见误区
🔗 相关词条Vue Router 路由从 URL 输入到页面渲染虚拟 DOM 与 Diff
← 返回来源章节前端路由原理(hash / history)