vue2.0 监听用户无操作页面停留时长然后弹窗提示

前言


在vue2.0项目中会遇到用户停留在某个页面长时间不操作的场景,针对此场景需要做某些操作。这边博文就讲讲是如何实现这个需求的。

可以在当前页面写,也可以采用mixins方法引入,我采用的mixins,是因为项目中多个页面用到

直接上代码

第一步,新建DurationStay.js
export const DurationStay = {
    data(){
      return {
        currentTime:"",
        DurationOfStay:5*60*1000,   //自定义的无操作时长5分钟
        intervalTime:0
      }
    },
    mounted(){
      this.currentTime = new Date().getTime();
      this.checkouttime();
      document.addEventListener("keydown",this.resetStartTime);
      document.addEventListener('touchstart',this.resetStartTime);
    },
  
    beforeDestroy(){
     //离开页面要销毁事件,否则会影响跳转的下个页面
      document.removeEventListener("keydown",this.resetStartTime);
      document.removeEventListener("touchstart",this.resetStartTime);
      if(this.intervalTime){
        clearInterval(this.intervalTime);
      }
    },
    methods:{
      resetStartTime(){
        this.currentTime = new Date().getTime();
      },
  
      checkouttime(){
        this.intervalTime= setInterval(()=>{
          let nowtime = new Date().getTime();
          if(nowtime - this.currentTime > this.DurationOfStay){
          	//特别注意:在这里要用自己独有的弹窗,不要跟项目的其他弹窗一直,否则会影响页面中别的弹窗弹起的bug
            this.$messagebox({
                title: "温馨提示",
                message: "页面停留太长,点击“刷新一下”获取最新价格和库存。",
                confirmButtonText: "刷新一下",
                closeOnClickModal:false,
            }).then(()=>{
            	//这里可以自由发挥,根据需求去做
                this.init();
            });
            return false;
          }
        },30000)
      }
    }
  }
  
第二步,在页面中引入
<script>
	import  { DurationStay } from './components/DurationStay';
	export default {
		 mixins:[ DurationStay ],
		 data(){
		 	return{}
		 }
	}
</script>

结束语

亲测有效。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值