Vue 實現監聽窗口關閉事件,并在窗口關閉前發送請求
網上很多博客說監聽窗口關閉事件使用window.beforeunload,但是這個監聽事件也會在頁面刷新的時候執行,經過百度和自己的實際測試,
終于解決了這個問題,代碼如下:
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不能執行同步請求。
補充知識:vue如何在用戶要關閉當前網頁時彈出提示
效果如下圖
正常 js 頁面處理方式
window.onbeforeunload = function (e) { e = e || window.event; // 兼容IE8和Firefox 4之前的版本 if (e) { e.returnValue = ’關閉提示’; } // Chrome, Safari, Firefox 4+, Opera 12+ , IE 9+ return ’關閉提示’;};
vue 中處理方式
let _this = this window.onbeforeunload = function (e) { if (_this.$route.name == 'dyyPerformanceCenterSale') { e = e || window.event; // 兼容IE8和Firefox 4之前的版本 if (e) { e.returnValue = ’關閉提示1111’; } // Chrome, Safari, Firefox 4+, Opera 12+ , IE 9+ return ’關閉提示222’; } else { window.onbeforeunload = null } };
針對很多同學說的沒有實現 ,我這里在詳細描述一下 方法寫在 mounted里面 ,然后 記得把route name替換成自己當前頁面。
以上這篇Vue 實現監聽窗口關閉事件,并在窗口關閉前發送請求就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
