在WebApp或浏览器中,会有点击返回、后退、上一页等按钮实现自己的关闭页面、调整到指定页面、确认离开页面或执行一些其它操作的需求。可以使用 popstate 事件进行监听返回、后退、上一页操作。
pushState() 的基本参数是:
window.history.pushState(state, title, url);
state:存储一个对象,可以添加相关信息,可以使用 history.state 读取其中的内容。
title:历史记录的标题(目前浏览器不支持)。
url:创建的历史记录的链接。进行历史记录操作时会跳转到该链接。
pushState() 配合 popstate 的监听
想要良好的支持浏览器的历史前进后退操作,应当部署popstate监听:
window.addEventListener('popstate', function, false);
具体实现逻辑:
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)
},
// 每次路由返回都会触发此方法
goBack () {
if (this.isSave) {
window.history.back()
return
}
// console.log("点击了浏览器的返回按钮")
if (this.$route.params.edit === 'edit' && (JSON.stringify(this.contracts.form) !== JSON.stringify(this.temp_data))) {
this.$confirm('当前内容尚未保存,是否确定关闭', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
window.history.back()
}).catch(() => {
// 每次返回都会消耗一个 history 实体,若用户选择取消离开,则需要继续 pushState 一个实体;
history.pushState(null, null, document.URL)
console.log('取消')
})
} else {
window.history.back()
}
},
实现效果:
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。