vue監(jiān)聽用戶是否待機(jī)無(wú)操作

在主界面使用混入(mixins)

export default {
  data() {
    return {
      logoutCount: 0
    }
  },
  computed: {
    // 系統(tǒng)設(shè)置的待機(jī)時(shí)間
    outTime() {
      return this.$store.state.settings.outTime
    }
  },
  mounted() {
    // 監(jiān)聽鼠標(biāo)
    document.onmousemove = event => {
      this.logoutCount = 0
    }
    // 監(jiān)聽鍵盤
    document.onkeydown = () => {
      this.logoutCount = 0
    }
    // 監(jiān)聽Scroll
    document.onscroll = () => {
      this.logoutCount = 0
    }
    this.setTimer()
  },
  // 清除定時(shí)器
  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分鐘無(wú)操作就自動(dòng)登出
      this.logoutCount++
      if (outTime - this.logoutCount < 10 && outTime - this.logoutCount > 0) { // 鎖定錢包倒計(jì)時(shí)
        this.$message.closeAll()
        this.$message({
          message: `系統(tǒng)已經(jīng)${this.outTime}分鐘無(wú)操作,將在${outTime - this.logoutCount}秒后鎖定錢包,如不想鎖定錢包,請(qǐng)任意操作鼠標(biāo)鍵盤`,
          type: 'error'
        })
      } else if (this.logoutCount > outTime) { // 鎖定錢包
        this.$message.closeAll()
        this.$message({
          message: `系統(tǒng)已經(jīng)${this.outTime}分鐘無(wú)操作,錢包自動(dòng)鎖定`,
          type: 'error',
          duration: 15000
        })
        await this.$store.dispatch('user/logout')
        this.$router.push(`/login?redirect=${this.$route.path}`)
      }
    }
  }
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容