**项目需求**: 在一定时间内用户未操作当前登录系统时,给予消息弹框提示,计时结束后退出登录
**实现思路**: 监听键盘、鼠标事件,有触发事件时,重置开始计时的时间;无事件触发,则判定当前系统属于无操作状态,`timeOut`时间后关闭消息弹框,退出登录,跳转至登录页
>[warning] tips: 本功能代码基于`vue`+`iview`框架实现,具体功能代码需根据具体框架
~~~
/**
* @description 一定时间内未操作系统时退出登录提示功能
* @param { number } timeOut 设置多久后提示即将退出登录,默认30分钟
* @param { number } time 设置消息提示框关闭时间,默认30秒
*/
import iview from "iview";
export default class ExitTip {
constructor(timeOut = 30 * 60 * 1000, time = 30) {
this.startTime = new Date().getTime();
this.timeOut = timeOut;
this.time = time; // 递减重置时间设置
this._time = time; // 递减时间设置
this.init();
}
init() {
const _this = this;
const resetTime = () => {
this.startTime = new Date().getTime();
const time = this.time;
this._time = time;
iview.Notice.close("exitTip");
};
this.addListener(resetTime);
this.timeInterVal = window.setInterval(() => {
const { timeOut, startTime, time, _time } = _this;
const currentTime = new Date().getTime();
if (currentTime - startTime > timeOut) {
if (_time > 0) {
if (_time < time) {
iview.Notice.close("exitTip");
}
iview.Notice.warning({
name: "exitTip",
title: "系统退出登录提示",
desc: `当前系统长时间未操作,将在 ${_time} 秒后退出登录,移动鼠标或操作键盘可取消退出`,
duration: 0
});
_this._time -= 1;
} else if (_time === 0) {
iview.Notice.close("exitTip");
window.clearInterval(_this.timeInterVal);
_this.removeListener(resetTime);
_this.handleExit();
}
}
}, 1000);
}
addListener(resetTime) {
window.addEventListener("keydown", resetTime);
window.addEventListener("mousemove", resetTime);
}
removeListener(resetTime) {
window.removeEventListener("keydown", resetTime);
window.removeEventListener("mousemove", resetTime);
}
// 提供给外部通知当前系统需要退出登录的事件
handleExit() {}
}
~~~
使用方法
~~~
import ExitTip from "@/utils/exitTip";
// ...
mounted() {
const exitTip = new ExitTip();
exitTip.handleExit = () => {
// 请求退出登录接口,跳转至登录页面
}
}
~~~