vue监听浏览器网页关闭和网页刷新

1、监听浏览器页面关闭/刷新事件

运用场景:浏览器页面关闭后删除local storage、session、cookie、发送请求等。

//绑定监听事件
mounted() {
    window.addEventListener('beforeunload', e => this.beforeunloadHandler(e))
}
methods: {
    beforeunloadHandler(e) {
      console.log('关闭后=>为所欲为')
    }
},
//页面销毁前解除监听
destroyed() {
    window.removeEventListener('beforeunload', e => this.beforeunloadHandler(e))
}

2、只监听浏览器关闭事件

data(){
    return{
          beforeUnload: '',
          Handler: ''
    }
}
mounted() {
   window.addEventListener('beforeunload', e => this.beforeunloadHandler(e))
   window.addEventListener('unload', e => this.unloadHandler(e))
},
destroyed() {
  window.removeEventListener('beforeunload', e => this.beforeunloadHandler(e))
  window.removeEventListener('unload', e => this.unloadHandler(e))
},
ethods: {
   beforeunloadHandler(){
      this.beforeUnload=new Date().getTime();
   },
   unloadHandler(e){
     this.Handler=new Date().getTime()-this.beforeUnload;
        //判断是窗口关闭还是刷新
        if(this.Handler<=5){
         console.log('为所欲为');
        }
      },
}

你可能感兴趣的:(vue,vue.js,javascript,前端)