我在做項目的時候,有一個需求,在離開(跳轉或者關閉)購物車頁面或者刷新購物車頁面的時候向服務器提交一次購物車商品數量的變化。
將提交的一步操作放到 beforeDestroy 鉤子函數中。
beforeDestroy() { console.log('銷毀組件') this.finalCart()},但是發現 beforeDestroy 只能監聽到頁面間的跳轉,無法監聽到頁面刷新和關閉標簽頁。
所以還是要借助 onbeforeunload 事件。
順便復習了一下 JavaScript 中的一些加載,卸載事件:
Vue中監聽頁面刷新和關閉
1. 在methods中定義事件方法:
methods: { beforeunloadFn(e) { console.log('刷新或關閉') // ... }}2. 在created 或者 mounted 生命周期鉤子中綁定事件
created() { window.addEventListener('beforeunload', e => this.beforeunloadFn(e))}3. 在 destroyed 鉤子卸載事件
destroyed() { window.removeEventListener('beforeunload', e => this.beforeunloadFn(e))}測試了頁面刷洗和關閉都能監聽到。
回到我自己的項目,可以使用 onbeforeunload 事件和 beforeDestroy 鉤子函數結合:
created() { this.initCart() window.addEventListener('beforeunload', this.updateHandler)},beforeDestroy() { this.finalCart() // 提交購物車的異步操作},destroyed() { window.removeEventListener('beforeunload', this.updateHandler)},methods: { updateHandler() { this.finalCart() }, finalCart() { // ... }}總結
以上所述是小編給大家介紹的Vue監聽頁面刷新和關閉功能,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復大家的!
新聞熱點
疑難解答