vue 锁屏功能主要代码

·  阅读 120
<script>
import { mapState, mapMutations } from "vuex";
export default {
  data() {
    return {
      timeOut: 1000 * 60 * 15, // 15分钟锁屏 1000 * 60 * 15
      timer: null
    }
  },
  computed: {
    ...mapState({
      isLock: 'isLock'
    })
  },
  mounted() {
    this.modalStatus()
  },
  methods: {
    ...mapMutations(["changeLockStatus"]),
    modalStatus () {
      // 首次设置用户正在使用时间
      localStorage.setItem('moveTime', Date.now())
      const isLock = localStorage.getItem('isLock') === 'true'
      // 修改store里面的状态
      this.changeLockStatus(isLock)
      this.resetTimer(isLock)
      this.bindMouseEvents()
    },
    // 重置定时器 - 未锁时开启定时器
    resetTimer (flag) {
      this.timer && clearTimeout(this.timer)
      if (!flag) {
        this.timer = setTimeout(this.checkLockStatus, 1000 * 60)
      }
    },
    // 鼠标绑定事件 - 每次监听到操作则重新定时
    bindMouseEvents () {
      document.onmousemove = () => {
        localStorage.setItem('moveTime', Date.now())
      }
      document.onkeyup = () => {
        localStorage.setItem('moveTime', Date.now())
      }
    },
    // 锁屏判断
    checkLockStatus () {
      const moveTime = localStorage.getItem('moveTime')
      const isLock = Date.now() - moveTime >= this.timeOut
      this.changeLockStatus(isLock)
      localStorage.setItem('isLock', isLock ? 'true' : 'false')
      this.resetTimer(isLock)
      if (isLock) {
        document.onmousemove = null
        document.onkeyup = null
      }
    }
  },
  beforeDestroy() {
    document.onmousemove = null
    document.onkeyup = null
    this.resetTimer()
  }
}
</script>

复制代码
分类:
前端
标签:
收藏成功!
已添加到「」, 点击更改