需求:
有些时候需要在当前窗口关闭或页面刷新时进行一些操作,尤其是当前窗口关闭时,要进行操作,比如调接口等。
MDN上对此有介绍:
开发:
需要对当前页面进行监听,监听当前页面是否触发了刷新或是关闭。此时就用到了生命周期钩子。
mounted() {
window.addEventListener('beforeunload', this.handleBeforeUnload);
},
destroyed() {
window.removeEventListener('beforeunload', this.handleBeforeUnload);
},
methods: {
async handleBeforeUnload(event) {
// 需要进行的操作,我这里用到了调取接口,接口请求是异步,异步请求需要时间,需要将异步改为同步,所以用了async和await
if (this.typeType === 'add') {
console.log('id参数', this.$refs["tab"].$refs["futian-info"].idList)
await unlock({
idList: this.$refs["tab"].$refs["futian-info"].idList
}).then(res => {
})
}
//下面两行代码时浏览器自带的弹窗,我这里不需要就隐藏了,请根据自己的需求情况
// event.preventDefault();
// event.returnValue = '';
}
}
在mounted钩子中使用beforeunload事件去监听当前页面进行的操作,当页面刷新或者当前窗口关闭时就触发了destroyed钩子,在destroyed钩子中对mounted钩子中的监听进行移除。
备注:
使用beforeunload事件时请查看MDN文档中对一些浏览器的适用,有些浏览器和版本并不适用beforeunload事件。