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

百度找了下,发现大部分都是这样写的,在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 '关闭提示';
          }
     }
}

如此问题就解决了,但是这样的提示样式不知道能不能进行改动,如知望告知!
在这里插入图片描述

Logo

前往低代码交流专区

更多推荐