Vue中監(jiān)聽窗口關(guān)閉事件并在窗口關(guān)閉前發(fā)送請求,代碼如下:
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))
},
methods: {
beforeunloadHandler(){
this._beforeUnload_time=new Date().getTime();
},
unloadHandler(e){
this._gap_time=new Date().getTime()-this._beforeUnload_time;
debugger
//判斷是窗口關(guān)閉還是刷新
if(this._gap_time<=5){
//如果是登錄狀態(tài),關(guān)閉窗口前,移除用戶
if(!this.showLoginButton){
$.ajax({
url: '/pictureweb/user/remove',
type: 'get',
async:false, //或false,是否異步
})
}
}
},
}
window.beforeunload事件在window.unload事件之前執(zhí)行。同時(shí)注意ajax請求方式必須為同步請求,所以不能使用axios,因?yàn)閍xios不能執(zhí)行同步請求。
分享一些技術(shù)學(xué)習(xí)視頻資料:https://pan.baidu.com/s/13dbR69NLIEyP1tQyRTl4xw
本文標(biāo)題:Vue中監(jiān)聽窗口關(guān)閉事件并在窗口關(guān)閉前發(fā)送請求-創(chuàng)新互聯(lián)
本文URL:http://chinadenli.net/article32/dcposc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供手機(jī)網(wǎng)站建設(shè)、響應(yīng)式網(wǎng)站、品牌網(wǎng)站制作、ChatGPT、搜索引擎優(yōu)化、網(wǎng)站設(shè)計(jì)公司
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容