最近做了一个需求,就是页面在长时间不操作时,要跳转到登录页面并且弹出提示。
需求梳理
- 监听鼠标移动以及键盘操作。
- 设置timer,timer到达指定值后进行跳转并提示。
- 开启timer并且关闭timer
项目背景
vue项目,引入element-ui插件。
实现
监听事件
// 监听鼠标
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
}
设置Timer
cookieTimeout () {
// 判断用户30分钟无操作就自动登出
let outTime = 30
this.count++
if (this.count === outTime * 60) {
if (getCookie('token') !== null) {
resetStorage()
this.clearTimer()
this.$router.replace({name: 'Login'})
} else {
this.count = 0
}
}
}
开启/关闭Timer
clearTimer () {
clearInterval(window.myTimer)
window.myTimer = null
},
setTimer () {
this.count = 0
if (!window.myTimer) {
window.myTimer = window.setInterval(this.cookieTimeout, 1000)
}
}
一定要设置window的timer并且不仅要clear还要将其赋值为null。
然后在需要的地方set和clear就可以啦~