开发场景:
在某些填写表单类型的页面要求有返回时要保存所填写内容的需求。
框架: vue2 + vant2
代码:
mounted() {
if (window.history && window.history.pushState) {
if(window.history.length>1){
const state = {
key: Math.random() * new Date().getTime()
}
window.history.pushState(state, null, document.URL)
}
//给window添加一个监听事件popstate,拦截返回键,并执行方法 backFn
window.addEventListener('popstate', this.backFn, false)
}
},
methods:{
backFn () {
// 返回执行逻辑 此处还可以添加对话框
const state = {
key: Math.random() * new Date().getTime()
}
window.history.pushState(state, null, document.URL)
this.$dialog.confirm({
title: '温馨提示',
message: '是否保存到草稿?',
confirmButtonText: '保存',
cancelButtonText:'不保存'
})
.then(() => {
//防止保存时用户填写错误,然后直接返回关闭页面
window.history.pushState(state, null, document.URL)
// 保存后的逻辑
})
.catch(() => {
//不保存的逻辑
})
}
}
最后要记得销毁监听事件
destroyed(){
//销毁监听
window.removeEventListener('popstate',this.backFn,false)
}
只有state一直在变化,点击返回的时候才能触发popstate
popstate事件不适合作为公共方法,需要每个页面去设置赋值