
vue项目main.js中引入
import { longTimeStopScreen } from './utils/common';
使用:
// 监听页面停留太长时间
window.onload = () => {
// 定义倒计时的时长
const time = 10; // 1分钟
// 执行函数(回调函数)
function fn(params) {
if (window.confirm('你已经停留很久了,是否重新登录!')) {
// 点击了确认 -- 清除定时器
longTimeStopScreen(false);
// 执行其他操作逻辑
} else {
// 点击了取消
console.log('取消', window.LTimer);
}
}
longTimeStopScreen(true, time, fn);
};
};
方法:
/**
* @description: 倒计时函数/清定时
* @param { Boolean } isTime 是否倒计时/清空倒计时
* @param {*} time 倒计时时间
* @param {*} callback 倒计时之后的回调
* @return {*} null
* @demo longTimestopScreen(true, time, () => {
* console.log('倒计时时间到了')
* })
*/
export const longTimeStopScreen = (isTime, time, callback) => {
let backUpTime = time;
/**
* @description: 倒计时函数/清定时
* @param {*} time 倒计时时间
* @param {*} callback 倒计时之后的回调
* @return {*} null
* @demo customInterval(true, time, () => {
* console.log('倒计时时间到了')
* })
*/
function customInterval(time, callback) {
if (window.LTimer) {
clearInterval(window.LTimer);
window.LTimer = null;
}
window.LTimer = setInterval(() => {
time--;
console.log('-------- 倒计时 --------', time);
if (time == 0) {
time = backUpTime; // 重置时间
callback();
}
}, 1000);
}
// 鼠标事件
function mouseEvent(e) {
// 鼠标移动就重置定时器重新倒计时
customInterval(backUpTime, callback);
}
if (isTime) {
// 定义全局定时器Id
window.LTimer = null;
// 加载就开始倒计时
customInterval(time, callback);
// 检测鼠标移动事件 监听鼠标移动就重置定时器重新倒计时
window.addEventListener('mousemove', mouseEvent);
} else {
// 移除监听事件并清除定时器(释放性能)
window.removeEventListener('mousemove', mouseEvent);
clearInterval(window.LTimer);
window.LTimer = null;
}
}
文章介绍了在Vue项目中,如何在main.js中设置一个功能,当用户停留过长时间后,页面会提示是否重新登录。这个功能通过一个名为longTimeStopScreen的方法实现,结合倒计时和鼠标移动事件来监控用户的活动状态。如果用户未进行任何操作达到预设时间,则会触发重新登录的确认对话框。
3924

被折叠的 条评论
为什么被折叠?



