??? 今日穿梭指南:兩種維度の路由宇宙
1. Hash 模式:錨點の量子隧道
// 手動創建路由監聽器
window.addEventListener('hashchange', () => { const path = location.hash.slice(1) || '/'; console.log('進入哈希宇宙:', path); renderComponent(path);
}); // 編程式導航
function navigateTo(path) { location.hash = `#${path}`;
} // 初始化路由
if (!location.hash) navigateTo('/home');
?? 宇宙特性:
- URL 格式:
http://domain.com/#/home
- 優點:
- 兼容性強(IE8+)
- 無需服務器配置
- 缺點:
- URL 不夠優雅
- 錨點功能沖突風險
2. History 模式:時空操縱術
// 監聽歷史記錄變化
window.addEventListener('popstate', (e) => { const path = location.pathname; console.log('時空回退至:', path); renderComponent(path);
}); // 主動跳轉(不觸發頁面刷新)
function historyPush(path) { history.pushState({ key: Date.now() }, '', path); renderComponent(path); // 需手動觸發渲染
} // 攔截鏈接點擊事件
document.body.addEventListener('click', (e) => { if (e.target.tagName === 'A') { e.preventDefault(); historyPush(e.target.href); }
});
?? 高階法則:
- URL 格式:
http://domain.com/home
- 必須配置服務器:
# Nginx 配置 location / { try_files $uri $uri/ /index.html; }