Vue 實(shí)現(xiàn)監(jiān)聽(tīng)窗口關(guān)閉事件,并在窗口關(guān)閉前發(fā)送請(qǐng)求
網(wǎng)上很多博客說(shuō)監(jiān)聽(tīng)窗口關(guān)閉事件使用window.beforeunload,但是這個(gè)監(jiān)聽(tīng)事件也會(huì)在頁(yè)面刷新的時(shí)候執(zhí)行,經(jīng)過(guò)百度和自己的實(shí)際測(cè)試,
終于解決了這個(gè)問(wèn)題,代碼如下:
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)閉窗口前,移除用戶(hù) if(!this.showLoginButton){ $.ajax({ url: ’/pictureweb/user/remove’, type: ’get’, async:false, //或false,是否異步 }) } } },}
window.beforeunload事件在window.unload事件之前執(zhí)行。同時(shí)注意ajax請(qǐng)求方式必須為同步請(qǐng)求,所以不能使用axios,因?yàn)閍xios不能執(zhí)行同步請(qǐng)求。
補(bǔ)充知識(shí):vue如何在用戶(hù)要關(guān)閉當(dāng)前網(wǎng)頁(yè)時(shí)彈出提示
效果如下圖
正常 js 頁(yè)面處理方式
window.onbeforeunload = function (e) { e = e || window.event; // 兼容IE8和Firefox 4之前的版本 if (e) { e.returnValue = ’關(guān)閉提示’; } // Chrome, Safari, Firefox 4+, Opera 12+ , IE 9+ return ’關(guān)閉提示’;};
vue 中處理方式
let _this = this window.onbeforeunload = function (e) { if (_this.$route.name == 'dyyPerformanceCenterSale') { e = e || window.event; // 兼容IE8和Firefox 4之前的版本 if (e) { e.returnValue = ’關(guān)閉提示1111’; } // Chrome, Safari, Firefox 4+, Opera 12+ , IE 9+ return ’關(guān)閉提示222’; } else { window.onbeforeunload = null } };
針對(duì)很多同學(xué)說(shuō)的沒(méi)有實(shí)現(xiàn) ,我這里在詳細(xì)描述一下 方法寫(xiě)在 mounted里面 ,然后 記得把route name替換成自己當(dāng)前頁(yè)面。
以上這篇Vue 實(shí)現(xiàn)監(jiān)聽(tīng)窗口關(guān)閉事件,并在窗口關(guān)閉前發(fā)送請(qǐng)求就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
