History路由的pushState,replaceState和popstate的区别
HTML5中引入了history.pushState()、history.replaceState()、popstate事件来处理浏览器历史记录的问题。我们可以通过上诉方法实现改变地址栏url的参数,实现页面不会刷新,但是页面上的数据实现更新。
1. history.state:
当前URL下对应的状态信息。如果当前URL不是通过pushState或者replaceState产生的,那么history.state是null 。
2. onpopstate 可以监听 state 的变化:
history.go 和 history.back(包括用户按浏览器历史前进后退按钮)触发popstate事件,事件发生时浏览器会从history中取出URL和对应的state对象替换当前的URL和history.state。popstate事件会造成页面刷新。
需要注意的是调用history.pushState()或history.replaceState()不会触发popstate事件。只有在做出浏览器动作时,才会触发该事件,如用户点击浏览器的回退按钮(或者在Javascript代码中调用history.back())
window.onpopstate = function(event){
if(history.state) {
console.log( '当前state:' event.state ); // { key:1}
console.log( 'url:' document.location ); // http://...?key=1
}
}
// 或者用addEventListener的方式监听popstate事件
window.addEventListener('popstate', e => {
const path = e.state && e.state.path;
this.routes[path] && this.routes[path]();
})
3. history.pushState(state, title, url)
将当前URL和history.state加入到 history 中,并用新的state和URL替换当前,不会造成页面刷新。当我们点击按钮发生URL变化时,便要调用history.pushState()方法
state:与要跳转到的URL对应的状态信息。
title:一般传空字符串 或 null 即可。
url:要跳转到的URL地址,不能跨域。
history.pushState({number: 123}, null, “/home”);
4. history.replaceState(state, title, url) :
用新的state和URL替换当前state,不会造成页面刷新。
state:与要跳转到的URL对应的状态信息。
title:一般传空字符串 或 null 即可。
url:要跳转到的URL地址,不能跨域。
history.replaceState({number: 123}, null, “/home”);
5. 总结
history.pushState:是H5的方法,用于向history.state中添加url信息
history.replaceState:是H5的方法,用于向history.state中替换url信息
popstate:是H5的事件,用于监听go和back事件,history.pushState()或history.replaceState()不会触发popstate事件