I was doing the project, there is a requirement to submit a number of changes to the server Cart products in time to leave (jump or close) the shopping cart page or refresh the shopping cart page.
The asynchronous operation submitted into beforeDestroy hook function.
beforeDestroy() {
console.log('销毁组件')
this.finalCart()
},复制代码
But we found beforeDestroy can only listen to jump between pages, not listening to refresh the page and close the tab.
It still must rely on onbeforeunload
events.
Incidentally brushed up some JavaScript loading, unloading event:
- Executed only when the page load
onload
event. - When the page is closed, the first
onbeforeunload
event, thenonunload
the event. - First perform a page refresh when the
onbeforeunload
event, thenonunload
the event, the lastonload
event.
Vue page refresh the monitor on and off
1. Define the event method in methods:
methods: {
beforeunloadFn(e) {
console.log('刷新或关闭')
// ...
}
}复制代码
2. binding events in the life cycle created or mounted hooks
created() {
window.addEventListener('beforeunload', e => this.beforeunloadFn(e))
}复制代码
3. Uninstall event destroyed hooks
destroyed() {
window.removeEventListener('beforeunload', e => this.beforeunloadFn(e))
}复制代码
Test and refresh the page can be turned off to listen to.
Back to my own project, you can use the onbeforeunload
event and the beforeDestroy
hook function in combination:
created() {
this.initCart()
window.addEventListener('beforeunload', this.updateHandler)
},
beforeDestroy() {
this.finalCart() // 提交购物车的异步操作},
destroyed() {
window.removeEventListener('beforeunload', this.updateHandler)},
methods: {
updateHandler() {
this.finalCart()
},
finalCart() {
// ...
}
}复制代码
Reproduced in: https: //juejin.im/post/5d0aee8ff265da1b8d162275