有这么一个需求,开发了一套系统,当用户离开桌面或者一段时间不操作的话,需要把该系统所有打开页面锁定起来,就跟桌面锁屏一样,只能输入密码验证成功后,或者重新登录,才可以继续操作页面,如果刷新页面,也要保持锁定。就像下图一样。当然用户也可以手动触发锁屏。目的是防止他人随意操作系统的重要内容。那么该如何去实现呢?
5s锁屏效果如下:
有点绕,需要好好捋一捋。
以下代码是不完全代码,html结构省略了,大家自由发挥。
// app.vue data () { return { timeOut: 5000, timer: null, isLock: 'false' } }, mounted () { this.timer = setTimeout(this.lockPro, this.timeOut) // 首次设置操作时间 localStorage.setItem('moveTime', Date.now()) // 首次判断状态 this.modalStatus() // 轮询监听状态 setInterval(this.modalStatus, 1000) // 监听鼠标事件 this.events() }, methods:{ events() { window.onmousemove = () => { // console.log('鼠标移动了') if (!this.isLock) { localStorage.setItem('moveTime', Date.now()) this.clearLocaPro('continue') } } }, modalStatus() { if (localStorage.getItem('isLock') === 'true') { // console.log('锁屏了') this.isLock = true this.clearLocaPro() } else { // console.log('当前没锁屏') this.isLock = false this.clearLocaPro('continue') } }, lockPro() { if (!this.timeOut) { localStorage.setItem('isLock', 'false') this.clearLocaPro('continue') return } if (Date.now() - localStorage.getItem('moveTime') < this.timeOut) { localStorage.setItem('isLock', 'false') this.clearLocaPro('continue') } else { localStorage.setItem('isLock', 'true') this.clearLocaPro() } }, clearLocaPro(status) { if(this.timer){ clearTimeout(this.timer) } if (status === 'continue') { this.timer = setTimeout(this.lockPro, this.timeOut) } }, // 手动锁定 handleLock(){ this.clearLocaPro() localStorage.setItem('isLock', 'true') }, // 密码解锁 unlock(){ localStorage.removeItem('isLock') localStorage.setItem('moveTime', Date.now()) this.clearLocaPro('continue') }, ... // 别忘了退出登录也要清除isLock }