vue 前端页面无操作时,系统退出登录的定时器设计

一、背景

我们平时做系统为了保证用户操作数据的安全性,很多时候当用户长时间不再操作电脑的时候,应该给用户自动退出系统,这样可以防止有别人使用电脑操作上一个用户的数据。

二、设计想法

  • 监听鼠标移动以及键盘操作。
  • 设置timer,timer到达指定值后进行跳转并提示。
  • 开启timer并且关闭timer

三、代码实现

设定一个计数值,利用js原生的事件,对鼠标,键盘进行监听,如果一有触发的鼠标,键盘的话,就将计数值清零,否则,计数值一直累加,当累加到一个目标值,即那个无操作退出系统的时间就可以触发退出系统函数。

完整的代码:

data () {
    return {
        count: 0
        }
},
mounted () {
    // 监听鼠标
    document.onmousemove = (event) => {
      let x1 = event.clientX
      let y1 = event.clientY
      if (this.x !== x1 || this.y !== y1) {
        this.count = 0
      }
      this.x = x1
      this.y = y1
    }
    // 监听键盘
    document.onkeydown = () => {
      this.count = 0
    }
    // 监听Scroll
    document.onscroll = () => {
      this.count = 0
    }
    this.setTimer()
  },
// 最后在beforeDestroy()生命周期内清除定时器:
  beforeDestroy () {
    this.clearTimer()
  },
methods: {
    clearTimer () {
      clearInterval(window.myTimer)
      window.myTimer = null
    },
    setTimer () {
      this.count = 0
      if (!window.myTimer) {
        window.myTimer = window.setInterval(this.cookieTimeout, 1000)
      }
    },
    cookieTimeout () {
    // 判断用户5分钟无操作就自动登出
      let outTime = 5
      this.count++
      if (this.count === outTime * 60) {
        this.$message({
          message: '系统已经五分钟无操作,将在十秒后退出登录,如不想退出系统,请任意操作鼠标键盘...',
          type: 'error'
        })
        setTimeout(this.logout, 10000)
        // console.log('aaaa', this.count)
      }
    },
    logout () {
      // console.log('bbb', this.count)
      if (this.count >= 5 * 60) {
        sessionStorage.setItem('loginname', '')
        this.$router.replace({name: 'Login'})
      }
    },
}

功能实现还是相对简单的,仅仅作为记录一下。

你可能感兴趣的:(vue 前端页面无操作时,系统退出登录的定时器设计)