Hash路由
- URL 结构:http://example.com/#/path,`# 后`的部分称为哈希(Hash)。
- 无刷新特性:浏览器不会将哈希部分发送到服务器,改变哈希值不会触发页面刷新。
- 事件驱动:URL 哈希部分变化, 监听
hashchange
事件,动态更新页面内容。
hashchange 事件:
- 作用:监听 URL 哈希值变化,触发页面更新。
示例:
js
window.addEventListener('hashchange', () => {
const currentHash = window.location.hash.substring(1); // 去掉 "#" 符号
console.log('当前路径:', currentHash); // 如 "/home"
renderPage(currentHash); // 根据路径渲染页面
});
手动触发哈希变化:
- 直接修改 window.location.hash 会触发 hashchange 事件:
js
// 跳转到 "#/profile"
window.location.hash = '/profile';
History 路由
- URL 结构:http://example.com/path,路径与真实 URL 一致。
- 无刷新跳转:通过
pushState()
或replaceState()
修改历史记录,不会触发页面重载。 - 事件驱动:监听
popstate
事件响应浏览器前进/后退操作。
- history.pushState(state, title, url)
作用:向浏览器历史记录栈添加新记录,URL 更新但页面不刷新。
参数:- state:与当前记录关联的状态对象(可用于 popstate 事件恢复页面状态)。
- title:大多数浏览器忽略此参数,可传空字符串。
- url:新路径(需符合同源策略)。
js
history.pushState({ page: 1 }, '', '/page1'); // URL 变为 /page1
- history.replaceState(state, title, url)
作用:替换当前历史记录,不添加新条目。
js
history.replaceState({ page: 2 }, '', '/page2'); // 当前记录替换为 /page2
- popstate 事件
触发条件:用户点击浏览器 前进/后退 按钮,或调用 history.back() / history.forward()。
注意:直接调用pushState()
或replaceState()
不会触发此事件。
js
// 前进/后退, 会触发popstate事件
window.addEventListener('popstate', () => {
const path = window.location.pathname;
renderPage(path);
});
pushState() 和 replaceState() 的本质作用
这两个方法属于 HTML5 History API,核心功能是 操作浏览器历史记录栈:
- pushState():向历史记录栈中添加一个新条目。
- replaceState():替换当前历史记录栈中的条目。
共同特性:- 仅修改 URL 和历史记录,不会刷新页面。
- 不会触发任何事件(包括 popstate)。
- 不会自动更新页面内容。
要让页面"跳转"(即内容切换),需开发者 手动将 URL 与页面状态同步,或者利用路由库(封装底层 API,实现 URL 与组件的自动同步)。
⚠️ history路由注意刷新404
问题
- History模式(如HTML5 History API)使用真实的URL路径(如
example.com/user/profile
),当用户刷新页面时,浏览器会向服务器请求这个完整路径。如果服务器没有配置正确的路由处理,就会返回404错误,因为服务器上可能并不存在这个物理路径对应的资源。 - Hash模式使用URL哈希值(如
example.com/#/user/profile
),浏览器在请求时只会发送哈希值前面的部分(example.com/
)到服务器,哈希值部分(#/user/profile
)不会被发送。因此无论哈希值如何变化,服务器始终接收到的是同一个请求,不会出现404问题。