Vue stepped pit tour (two) - listening and off page refresh

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 onbeforeunloadevents.

Incidentally brushed up some JavaScript loading, unloading event:

  • Executed only when the page load onloadevent.
  • When the page is closed, the first onbeforeunloadevent, then onunloadthe event.
  • First perform a page refresh when the onbeforeunloadevent, then onunload the event, the last onload 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  onbeforeunloadevent and the beforeDestroyhook 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

Guess you like

Origin blog.csdn.net/weixin_34346099/article/details/93176285