区分页面是页面刷新还是页面关闭

<template>
  <div id="app"></div>
</template>

<script>

export default {
  name: "App",
  data() {
    return {
      beforeunloadTime: 0,
      unloadTime: 0
    };
  },
  mounted() {
    window.addEventListener('beforeunload', e => this.beforeunloadHandler(e));
    window.addEventListener('unload', e => this.unload(e));
  },
  destroyed() {
    window.removeEventListener('beforeunload', e => this.beforeunloadHandler(e));
    window.removeEventListener('unload', e => this.unload(e));
  },
  methods: {
    beforeunloadHandler() {
      this.beforeunloadTime = new Date().getTime()
    },
    unload() {
      this.unloadTime = new Date().getTime()
      // window.localStorage.setItem('timer', String(this.unloadTime - this.beforeunloadTime))
      // 本地通过localStorage中的数据看出,关闭事件间隔小于1,刷新则大于8
      if (this.unloadTime - this.beforeunloadTime <= 1) {
        // 执行退出登录
        this.logout(true)
      }
    }
  }
};
</script>

VUE——监听浏览器关闭及标签页关闭事件 - 。思索 - 博客园 (cnblogs.com)

 离开当前路由时,提示是否要离开当前页面

beforeRouteLeave(to, form, next) {
    this.$confirm('正在处理消息,请确认是否离开?', { // element-ui 确认对话框为例
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(async () => {
      this.beforeunloadHandler()  // 业务需要,可在此写入
      next() // 点击确定,确认离开
    })
    .catch(() => {
      location.reload()  // 刷新页面 业务需要
      next(false) // 点击取消,不离开当前页面
    })
      return
 },

Vue 拦截离开页面操作 | Vue-Demo-Collection (gesj-yean.github.io)

  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值