Vue 實現(xiàn)監(jiān)聽窗口關(guān)閉事件,并在窗口關(guān)閉前發(fā)送請求
網(wǎng)上很多博客說監(jiān)聽窗口關(guān)閉事件使用window.beforeunload,但是這個監(jiān)聽事件也會在頁面刷新的時候執(zhí)行,經(jīng)過百度和自己的實際測試,
終于解決了這個問題,代碼如下:
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í)行。同時注意ajax請求方式必須為同步請求,所以不能使用axios,因為axios不能執(zhí)行同步請求。
補(bǔ)充知識:vue如何在用戶要關(guān)閉當(dāng)前網(wǎng)頁時彈出提示
效果如下圖
正常 js 頁面處理方式
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 } };
針對很多同學(xué)說的沒有實現(xiàn) ,我這里在詳細(xì)描述一下 方法寫在 mounted里面 ,然后 記得把route name替換成自己當(dāng)前頁面。
以上這篇Vue 實現(xiàn)監(jiān)聽窗口關(guān)閉事件,并在窗口關(guān)閉前發(fā)送請求就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。
