1.hash 模式 实际上用到的是window.location
让我们一起来看看window.location是个啥吧,它是一个对象,里面有重要的几个参数,hash('#' 包括后面的参数,我们改变hash时也是通过window.location.hash = 'xxx') / host / href(当前url)
window监听window.location.hash改变的方法 ==> hashchange
// 浏览器监听hash
window.addEventListener("hashchange", val => { console.log(val) })
这个val是一个新的location对象里面有新的url和旧的url
// 修改hash值
window.location.hash = "123"
// 浏览器执行这段代码之后,url后面会多"#123" 并且会触发监听事件
缺点:
不能传值
2.history模式
让我们看看window.history到底是个啥吧,它是一个对象,它的第一层属性有length(当前history路由栈的长度) state 当前url的参数, 他的__proto_原型里面有几个方法,用来进行路由的跳转, ① pushState(传递的参数, title[一般都是null], './xx'[跳转路径,可以是绝对路径也可以是相对路径,绝对路径会覆盖url中host后面的参数, 相对路径会在最后面加上xx] ) ,它会在history中增加一个历史路由, 它不会触发window的popState方法②replace参数跟pushState一样,只是他路由跳转方式是替换当前的路由,它不会触发window的popState方法 ③ back()history路由返回一级 (此时url前面还有路由)④forward history路由向前走一级 (此时url后面还有路由) ⑤go() 向前或者向后路由跳转
// 浏览器监听history
window.addEventListener("popstate", val => { console.log(val) })
//
window.history.pushState(state, title, url)
// state:需要保存的数据,可以通过window.history.state获取
// title:标题,基本没用,一般传 null
// url:设定新的历史记录的 url。新的 url 与当前 url 的 origin 必须是一樣的,否则会抛出错误。url可以是绝对路径,也可以是相对路径。
//如 当前url是 https://www.baidu.com/b/,执行history.pushState(null, null, './qq/'),则变成 https://www.baidu.com/b/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.back() // 后退
window.history.forward() // 前进
window.history.go(1) // 前进一步,-2为后退两步,window.history.length可以查看当前历史堆栈中页面的数量
优点: 可以进行传值