history 路由和 hash 路由
hash 路由
hash 路由,在 html5 前,为了解决单页路由跳转问题采用的方案, hash 的变化不会触发页面渲染,服务端也无法获取到 hash 值,前端可通过监听 hashchange 事件来处理 hash 值的变化
text
window.addEventListener('hashchange', function(){
// 监听hash变化,点击浏览器的前进后退会触发
})window.addEventListener('hashchange', function(){
// 监听hash变化,点击浏览器的前进后退会触发
})history 路由
history 路由,是 html5 的规范,提供了对
history栈中内容的操作,常用 api 有:
js
window.history.pushState(state, title, url)
// let currentState = history.state; 获取当前state
// state:需要保存的数据,这个数据在触发popstate事件时,可以在event.state里获取
// title:标题,基本没用,一般传 null
// url:设定新的历史记录的 url。新的 url 与当前 url 的 origin 必须是一樣的,否则会抛出错误。url可以是绝对路径,也可以是相对路径。
//如 当前url是 https://www.baidu.com/a/,执行history.pushState(null, null, './qq/'),则变成 https://www.baidu.com/a/qq/,
//执行history.pushState(null, null, '/qq/'),则变成 https://www.baidu.com/qq/
window.history.replaceState(state, title, url)
// 与 pushState 基本相同,但她是修改当前历史记录,而 pushState 是创建新的历史记录
window.addEventListener('popstate', function () {
// 监听浏览器前进后退事件,pushState 与 replaceState 方法不会触发
})window.history.pushState(state, title, url)
// let currentState = history.state; 获取当前state
// state:需要保存的数据,这个数据在触发popstate事件时,可以在event.state里获取
// title:标题,基本没用,一般传 null
// url:设定新的历史记录的 url。新的 url 与当前 url 的 origin 必须是一樣的,否则会抛出错误。url可以是绝对路径,也可以是相对路径。
//如 当前url是 https://www.baidu.com/a/,执行history.pushState(null, null, './qq/'),则变成 https://www.baidu.com/a/qq/,
//执行history.pushState(null, null, '/qq/'),则变成 https://www.baidu.com/qq/
window.history.replaceState(state, title, url)
// 与 pushState 基本相同,但她是修改当前历史记录,而 pushState 是创建新的历史记录
window.addEventListener('popstate', function () {
// 监听浏览器前进后退事件,pushState 与 replaceState 方法不会触发
})
Cao Note