前端小食堂 | Day10 - 前端路由の时空裂隙
🕳️ 今日穿梭指南:两种维度の路由宇宙
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; }