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() {
    
    
  window.addEventListener('beforeunload', this.beforeunloadFn())
},
destroyed() {
    
    
  window.removeEventListener('beforeunload', this.beforeunloadFn())
},
methods: {
    
    
  gotoPage(path){
    
    
    this.$router.push(path);

    this.$store.state.iframeSrc = this.$route.meta.link;
    this.$store.state.iframeTitle = this.$route.meta.title;
  },
  beforeunloadFn() {
    
    
    console.log('刷新或关闭');

    if(this.$route.path == '/system/knowledgeGraph') {
    
    
      this.gotoPage(this.graphItems.path);
    }
  }
}

猜你喜欢

转载自blog.csdn.net/qq_32755875/article/details/112308673