我在作項目的時候,有一個需求,在離開(跳轉或者關閉)購物車頁面或者刷新購物車頁面的時候向服務器提交一次購物車商品數量的變化。javascript
將提交的異步操做放到 beforeDestroy 鉤子函數中。java
beforeDestroy() {
console.log('銷燬組件')
this.finalCart()
},複製代碼
可是發現 beforeDestroy 只能監聽到頁面間的跳轉,沒法監聽到頁面刷新和關閉標籤頁。服務器
因此仍是要藉助 onbeforeunload
事件。異步
順便複習了一下 JavaScript 中的一些加載,卸載事件:函數
onload
事件。onbeforeunload
事件,再 onunload
事件。onbeforeunload
事件,而後 onunload
事件,最後 onload
事件。1. 在methods中定義事件方法:測試
methods: {
beforeunloadFn(e) {
console.log('刷新或關閉')
// ...
}
}複製代碼
2. 在created 或者 mounted 生命週期鉤子中綁定事件ui
created() {
window.addEventListener('beforeunload', e => this.beforeunloadFn(e))
}複製代碼
3. 在 destroyed 鉤子中卸載事件
this
destroyed() {
window.removeEventListener('beforeunload', e => this.beforeunloadFn(e))
}複製代碼
測試了頁面刷新和關閉都能監聽到。spa
回到我本身的項目,能夠使用 onbeforeunload
事件和 beforeDestroy
鉤子函數結合:code
created() {
this.initCart()
window.addEventListener('beforeunload', this.updateHandler)
},
beforeDestroy() {
this.finalCart() // 提交購物車的異步操做},
destroyed() {
window.removeEventListener('beforeunload', this.updateHandler)},
methods: {
updateHandler() {
this.finalCart()
},
finalCart() {
// ...
}
}複製代碼