**項目需求**: 在一定時間內用戶未操作當前登錄系統時,給予消息彈框提示,計時結束后退出登錄
**實現思路**: 監聽鍵盤、鼠標事件,有觸發事件時,重置開始計時的時間;無事件觸發,則判定當前系統屬于無操作狀態,`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 = () => {
// 請求退出登錄接口,跳轉至登錄頁面
}
}
~~~