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