vue 监听窗口关闭


需求:需要用户关闭窗口时,弹出提示确认,如此则需要监听窗口关闭了

百度找了下,发现大部分都是这样写的,在mounted里面添加监听事件

  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))
  },
  methods: {
    beforeunloadHandler(e){
      this._beforeUnload_time = new Date().getTime();
      //e.returnValue = '关闭提示'; 弹窗
    },
    unloadHandler(e){
      this._gap_time = new Date().getTime() - this._beforeUnload_time;
      //判断是窗口关闭还是刷新
      if (this._gap_time <= 5) {
        let datas = {
          objCode:null,
          opertion:'退出登录ajax',
          param:null,
          path:null,,}
        datas =  JSON.stringify(datas)
        $.ajax({
          url: this.$apiUrl.user.oper,
          type: 'post',
          contentType:'application/json',
          data:datas,
          dataType: "json",
          async: false, //或false,是否异步
        })
      }
    },
  },

 

但是我试了下并没有用,然后找到这个方法解决了

mounted(){
    this.watchTabUnload()
},
methods:{
    watchTabUnload(){
          window.onbeforeunload = function() {
            return '关闭提示';
          }
     }
}

这样在关闭的时候就会弹出如下提示了

微信截图_20220613181240.png

 


vue-element-ui 弹出页面层

vue-element/umyui 监听表格列宽变化

评 论
更换验证码