VUE 检测用户20秒内不进行操作倒计时退出

1.封装方法(需要自己在vuex中设置actions方法,全局储存outTime)

// 设置倒计时的时间(单位:秒)
let countDown; // 定时器 ID
let countDownSeconds; // 定时器 秒数
let originalTime   //传入的原始秒数,用于恢复定时
export function timeOut(seconds){
	if(seconds) originalTime = countDownSeconds = seconds  
	 countDown = setInterval(function() {
	  // 计算剩余秒数
	  countDownSeconds--;
	  // 输出倒计时
	  store.dispatch("setOutTime", 
		countDownSeconds,
	  );
	// 
	if (countDownSeconds  == 10) {
		Message.warning('当前无操作,将在10秒后登出系统')
	  }
	  // 判断倒计时是否结束,登出系统
	  if (countDownSeconds <= 0) {
		// 清除localStorage中的数据
		localStorage.clear();
		// 清除sessionStorage中的数据
		sessionStorage.clear();
		router.push({ name: 'home'})
	  }
	}, 1000);
  }
  export function clearTimeOut(){
	if(countDown) clearInterval(countDown);
  }

  export function touchEvent(){
	// 判断设备是否支持touch事件
	const isTouchDevice = 'ontouchstart' in window
	const isClickEventSupported = 'onclick' in document.documentElement
	if (isTouchDevice) {
	// 设备支持触摸事件
	window.addEventListener('touchstart', function(event) {
		console.log('用户激活touch事件');
		// 处理触摸事件
		if(countDown){ clearInterval(countDown)}
		timeOut(originalTime)
	})
	} else if (isClickEventSupported) {
	// 设备不支持触摸事件,但支持点击事件
	window.addEventListener('click', function(event) {
		// 处理点击事件
		if(countDown){ clearInterval(countDown)}
		timeOut(originalTime)
	})
	} else {
		// 设备既不支持触摸事件也不支持点击事件
		console.log('该设备不支持触摸事件和点击事件')
		}
  }

2.在main.js 引用触摸事件来使系统进行操作监控

iimport {touchEvent} from '@/utils/index'

touchEvent() //全局触发点击和触摸事件,触发倒计时退出系统

3.router.js 引用倒计时

import { clearTimeOut,timeOut } from "@/utils/index";

routers.beforeEach((to, from, next) => {
  // 每个页面都支持定制倒计时时间,没有定制的统一为200秒,统一的逻辑为20秒内没有操作,进行倒计时退出
  let timeObj = {
    'login':80,
  }
  // 除了hoem页面外其他的页面都需要进行倒计时,防止用户没有进行操作
  // 每个页面进入前都清除掉计数器
  clearTimeOut()
  if(to.name!=='home'){
    timeOut(timeObj[to.name] || 200)
  }
  next();
});

4.页面引用

<div class="countdown-text" v-show="countdown <= 60 && countdown !== 0">({{countdown}}S)</div>


 computed: {
    countdown() {
      return this.$store.state.app.outTime || 0
    }
  },

6.效果图

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值