需求:在关闭浏览器时发送接口,清除数据,需要用到的事件是【beforeunload】和【unload】。 需要注意的是: 【beforeunload】:在刷新和关闭时都会触发 【unload】:正在卸载时触发 1、为了安全,界面交互无效 (window.open, alert, confirm 等.),2、需要使用同步的方式请求接口,保证接口请求完成后页面关闭,或者使用fetch中有个属性【keepalive: true】
// 在mounted中监听事件
window.addEventListener('beforeunload', e => this.beforeunloadHandler(e))
window.addEventListener('unload', e => this.unloadHandler(e))
// 在destroyed中移除事件
window.removeEventListener('beforeunload', e => this.beforeunloadHandler(e))
window.removeEventListener('unload', e => this.unloadHandler(e))
beforeunloadHandler () {
this.beforeUnloadTime = new Date().getTime()
},
unloadHandler () {
const gapTime = new Date().getTime() - this.beforeUnloadTime
// 区分浏览器刷新还是关闭
if (gapTime <= 5) {
const url = `url`
fetch(url, {
headers: {
'X-Access-Token': token,
'content-type': 'application/json;charset=UTF-8'
},
method: 'DELETE',
keepalive: true
})
}
}