Vue監(jiān)聽頁面刷新和關(guān)閉功能
我在做項目的時候,有一個需求,在離開(跳轉(zhuǎn)或者關(guān)閉)購物車頁面或者刷新購物車頁面的時候向服務(wù)器提交一次購物車商品數(shù)量的變化。
將提交的一步操作放到 beforeDestroy 鉤子函數(shù)中。
beforeDestroy() { console.log('銷毀組件')
this.finalCart()},
但是發(fā)現(xiàn) beforeDestroy 只能監(jiān)聽到頁面間的跳轉(zhuǎn),無法監(jiān)聽到頁面刷新和關(guān)閉標簽頁。
所以還是要借助 onbeforeunload 事件。
順便復(fù)習了一下 JavaScript 中的一些加載,卸載事件:
- 頁面加載時只執(zhí)行 onload 事件。
- 頁面關(guān)閉時,先 onbeforeunload 事件,再 onunload 事件。
- 頁面刷新時先執(zhí)行 onbeforeunload 事件,然后 onunload 事件,最后 onload 事件。
Vue中監(jiān)聽頁面刷新和關(guān)閉
1. 在methods中定義事件方法:
methods: {
beforeunloadFn(e) {
console.log('刷新或關(guān)閉')
// ...
}
}
2. 在created 或者 mounted 生命周期鉤子中綁定事件
created() {
window.addEventListener('beforeunload', e => this.beforeunloadFn(e))
}
3. 在 destroyed 鉤子卸載事件
destroyed() {
window.removeEventListener('beforeunload', e => this.beforeunloadFn(e))
}
測試了頁面刷洗和關(guān)閉都能監(jiān)聽到。
回到我自己的項目,可以使用 onbeforeunload 事件和 beforeDestroy 鉤子函數(shù)結(jié)合:
created() {
this.initCart()
window.addEventListener('beforeunload', this.updateHandler)
},
beforeDestroy() {
this.finalCart() // 提交購物車的異步操作},
destroyed() {
window.removeEventListener('beforeunload', this.updateHandler)},
methods: {
updateHandler() {
this.finalCart()
},
finalCart() {
// ...
}
}
總結(jié)
以上所述是小編給大家介紹的Vue監(jiān)聽頁面刷新和關(guān)閉功能,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復(fù)大家的!
相關(guān)文章
vue中this.$http.post()跨域和請求參數(shù)丟失的解決
這篇文章主要介紹了vue中this.$http.post()跨域和請求參數(shù)丟失的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04
vue?element-plus中el-input修改邊框border的方法
element樣式還是蠻好的,只是有時候我們需要做一些調(diào)整,比如el-input的邊框,下面這篇文章主要給大家介紹了關(guān)于vue?element-plus中el-input修改邊框border的相關(guān)資料,需要的朋友可以參考下2022-09-09
vue-cli開發(fā)時,關(guān)于ajax跨域的解決方法(推薦)
下面小編就為大家分享一篇vue-cli開發(fā)時,關(guān)于ajax跨域的解決方法(推薦),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-02-02

