Vue监听页面刷新和关闭功能

今天药忘吃喽~ 2021-11-02 17:06 734阅读 0赞

我在做项目的时候,有一个需求,在离开(跳转或者关闭)购物车页面或者刷新购物车页面的时候向服务器提交一次购物车商品数量的变化。
将提交的一步操作放到 beforeDestroy 钩子函数中。

  1. beforeDestroy() { console.log('销毁组件'
  2. this.finalCart()},

但是发现 beforeDestroy 只能监听到页面间的跳转,无法监听到页面刷新和关闭标签页。
所以还是要借助 onbeforeunload 事件。
顺便复习了一下 JavaScript 中的一些加载,卸载事件:
页面加载时只执行 onload 事件。
页面关闭时,先 onbeforeunload 事件,再 onunload 事件。
页面刷新时先执行 onbeforeunload 事件,然后 onunload 事件,最后 onload 事件。
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 钩子函数结合:

  1. created() {
  2. this.initCart()
  3. window.addEventListener('beforeunload', this.updateHandler)
  4. },
  5. beforeDestroy() {
  6. this.finalCart() // 提交购物车的异步操作},
  7. destroyed() {
  8. window.removeEventListener('beforeunload', this.updateHandler)},
  9. methods: {
  10. updateHandler() {
  11. this.finalCart()
  12. },
  13. finalCart() {
  14. // ...
  15. }
  16. }

在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,734人围观)

还没有评论,来说两句吧...

相关阅读