vue监听用户是否待机无操作

在主界面使用混入(mixins)

export default {
  data() {
    return {
      logoutCount: 0
    }
  },
  computed: {
    // 系统设置的待机时间
    outTime() {
      return this.$store.state.settings.outTime
    }
  },
  mounted() {
    // 监听鼠标
    document.onmousemove = event => {
      this.logoutCount = 0
    }
    // 监听键盘
    document.onkeydown = () => {
      this.logoutCount = 0
    }
    // 监听Scroll
    document.onscroll = () => {
      this.logoutCount = 0
    }
    this.setTimer()
  },
  // 清除定时器
  beforeDestroy() {
    this.clearTimer()
  },
  methods: {
    clearTimer() {
      clearInterval(window.logoutTimer)
      window.logoutTimer = null
    },
    setTimer() {
      this.logoutCount = 0
      if (!window.logoutTimer) {
        window.logoutTimer = window.setInterval(this.logout, 1000)
      }
    },
    async logout() {
      const outTime = this.outTime * 60
      // 判断用户N分钟无操作就自动登出
      this.logoutCount++
      if (outTime - this.logoutCount < 10 && outTime - this.logoutCount > 0) { // 锁定钱包倒计时
        this.$message.closeAll()
        this.$message({
          message: `系统已经${this.outTime}分钟无操作,将在${outTime - this.logoutCount}秒后锁定钱包,如不想锁定钱包,请任意操作鼠标键盘`,
          type: 'error'
        })
      } else if (this.logoutCount > outTime) { // 锁定钱包
        this.$message.closeAll()
        this.$message({
          message: `系统已经${this.outTime}分钟无操作,钱包自动锁定`,
          type: 'error',
          duration: 15000
        })
        await this.$store.dispatch('user/logout')
        this.$router.push(`/login?redirect=${this.$route.path}`)
      }
    }
  }
}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容