做为一个辣鸡前端开发(我说我本身呢),仍是用vue技术栈的,不学一学路由知识,开发的时候页面飞到哪儿去了你都不知道。前端
利用支持h5 history属性的浏览器特性,它表示当前窗口的历史。vue
History.length // 当前窗口访问过页面的数量
History.state // 当前窗口历史的栈顶数据vue-router
History·back() // 后退一页
History.forward() //前进一页
HIstory.go(n: number) //前进(N>0)后退(n<0)n步浏览器
History.pushState(state, title, url) //历史记录中添加一条记录
History.replaceState(state, title, url) // 替换当前记录markdown
state:一个与添加的记录相关联的状态对象,主要用于popstate事件。该事件触发时,该对象会传入回调函数。也就是说,浏览器会将这个对象序列化之后保留在本地,从新载入这个页面的时候,能够拿到这个对象。若是不须要这个对象,此处能够填null。
title:新页面的标题。可是,如今全部浏览器都忽视这个参数,因此这里能够填空字符串。
url:新的网址,必须与当前页面处在同一个域。浏览器的地址栏将显示这个网址。函数
History.popstate()
每当同一个文档的浏览历史(即history对象)出现变化时,就会触发popstate事件。学习
注意,仅仅调用pushState()方法或replaceState()方法 ,并不会触发该事件,只有用户点击浏览器倒退按钮和前进按钮,或者使用 JavaScript 调用History.back()、History.forward()、History.go()方法时才会触发。另外,该事件只针对同一个文档,若是浏览历史的切换,致使加载不一样的文档,该事件也不会触发。ui
使用的时候,能够为popstate事件指定回调函数。url
window.onpopstate = function(event) {
console.log('location: ' + document.location);
console.log('state: ' + JSON.stringify(event.state));
}
// 或者
window.addEventListener("popstate", function() {
console.log('location: ' + document.location);
console.log('state: ' + JSON.stringify(event.state));
})
复制代码
回调函数的参数是一个event事件对象,它的state属性指向pushState和replaceState方法为当前 URL 所提供的状态对象(即这两个方法的第一个参数)。上面代码中的event.state,就是经过pushState和replaceState方法,为当前 URL 绑定的state对象。spa
var currentState = history.state;
原理是onhashchange事件,url都会被浏览器记录下来,只能改变#后面的url片断
window.onhashchange = function(event){
console.log(event.oldURL, event.newURL);
let hash = location.hash.slice(1);
document.body.style.color = hash;
}
复制代码