vue監(jiān)聽瀏覽器網(wǎng)頁關閉和網(wǎng)頁刷新事件代碼示例
更新時間:2023年08月11日 11:00:58 作者:衫褲泡露
在前端開發(fā)中我們通常會遇到這樣的需求,用戶離開、刷新頁面前,修改數(shù)據(jù)未進行保存操作,需要提示框提醒用戶,這篇文章主要給大家介紹了關于vue監(jiān)聽瀏覽器網(wǎng)頁關閉和網(wǎng)頁刷新事件的相關資料,需要的朋友可以參考下
1、監(jiān)聽瀏覽器頁面關閉/刷新事件
運用場景:瀏覽器頁面關閉后刪除local storage、session、cookie、發(fā)送請求等。
//綁定監(jiān)聽事件
mounted() {
window.addEventListener('beforeunload', e => this.beforeunloadHandler(e))
}
methods: {
beforeunloadHandler(e) {
console.log('關閉后=>為所欲為')
}
},
//頁面銷毀前解除監(jiān)聽
destroyed() {
window.removeEventListener('beforeunload', e => this.beforeunloadHandler(e))
}2、只監(jiān)聽瀏覽器關閉事件
data(){
return{
beforeUnload: '',
Handler: ''
}
}
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))
},
ethods: {
beforeunloadHandler(){
this.beforeUnload=new Date().getTime();
},
unloadHandler(e){
this.Handler=new Date().getTime()-this.beforeUnload;
//判斷是窗口關閉還是刷新
if(this.Handler<=5){
console.log('為所欲為');
}
},
}總結(jié)
到此這篇關于vue監(jiān)聽瀏覽器網(wǎng)頁關閉和網(wǎng)頁刷新事件的文章就介紹到這了,更多相關vue監(jiān)聽瀏覽器網(wǎng)頁關閉內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
解決vue.js出現(xiàn)Vue.js not detected錯誤的問題
這篇文章主要介紹了解決vue.js出現(xiàn)Vue.js not detected錯誤的問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10
Vue將數(shù)組轉(zhuǎn)換為樹形結(jié)構(gòu)的兩種實現(xiàn)方式
這篇文章主要介紹了Vue將數(shù)組轉(zhuǎn)換為樹形結(jié)構(gòu)的兩種實現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-06-06
解決vue-cli webpack打包開啟Gzip 報錯問題
這篇文章主要介紹了vue-cli webpack打包開啟Gzip 報錯問題的解決方法,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-07-07

