需要:
用户长时间不再操作电脑的时候,应该给用户主动退出零碎,这样能够避免有他人应用电脑操作上一个用户的数据。
或用户长时间不操作,暗藏鼠标等。
思路
- 监听鼠标挪动以及键盘操作。
- 设置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'}) } },}