• 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)
          }
        }
      }
      
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    第二步,在页面中引入
    <script>
    	import  { DurationStay } from './components/DurationStay';
    	export default {
    		 mixins:[ DurationStay ],
    		 data(){
    		 	return{}
    		 }
    	}
    </script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    结束语

    亲测有效。

  • 相关阅读:
    「PAT乙级真题解析」Basic Level 1087 有多少不同的值 (问题分析+完整步骤+伪代码描述+提交通过代码)
    线程中不安全的集合
    解决Windows下调试RTKLIB打开串口失败的问题
    Autovue集成全过程
    Redis
    MetaObjectHandler的使用
    批量处理文件夹及子文件夹下文件名
    mysql 添加外键约束
    sklearn基础篇(七)-- 随机森林(Random forest)
    Ae 效果:CC Snowfall
  • 原文地址:https://blog.csdn.net/ww_5211314/article/details/133764154