- 监听返回
mounted () {
if (window.history && window.history.pushState) {
// 向历史记录中插入了当前页
history.pushState(null, null, document.URL);
window.addEventListener('popstate', this.goBack, false);
}
},
destroyed () {
window.removeEventListener('popstate', this.goBack, false);
},
methods: {
goBack () {
// console.log("点击了浏览器的返回按钮");
sessionStorage.clear();
window.history.back(); history.pushState(null, null, document.URL); }, }
- 禁用返回
mounted () {
if (window.history && window.history.pushState) {
// 向历史记录中插入了当前页
history.pushState(null, null, document.URL);
window.addEventListener('popstate', this.goBack, false);
}
},
destroyed () {
window.removeEventListener('popstate', this.goBack, false);
},
methods: {
goBack () {
// console.log("点击了浏览器的返回按钮");
history.pushState(null, null, document.URL);
},
}
- history对象
window可以省略,直接使用history
1、window.history.back() || window.history.go(-1): 后退
2、window.history.forward() || window.history.go(1): 前进
3、window.history.go(num) : 前进或后退指定数量历史记录 window.history.go(0) 刷新
4、window.history.pushState(state, title, url) 存储当前历史记录点
state:一个对象,可以添加相关信息
title:历史记录的标题
url:创建的历史记录的链接
5、window.history.replaceState(state, title, url) 替换当前历史记录点
6、popstate history 实体改变时触发的事件,监听历史记录点
7、window.history.state 获取 history 实体中的 state 对象
- history.go(0) 和 location.reload() 的区别
location.reload() 默认参数为false,即location.reload(false)
location.reload(false):会用 HTTP 头 If-Modified-Since 来检测服务器上的文档是否已改变,如果文档已改变,从服务端再次下载该文档 如果文档未改变,从缓存中装载文档 ,作用等同于点击浏览器的刷新按钮 (F5)
location.reload(true): 绕过缓存,从服务器上重新下载该文档,作用等同于点击浏览器的刷新按钮,同时按住Shift (Shift+F5)
history.go(0) : 直接读取缓存数据,不会从服务器端获取数据
- history.go(-1) 和 history.back() 的区别
1.history.go(-1) 后退并刷新,原页面表单中的内容会丢失
2.history.back() 后退,原页面表单中的内容会保留