【已解决】VUE 轮询、轮询终止 beforeRouteLeave

目录

1 在data中定义

2 在methods中定义

3 开始轮询

4 终止轮询

方法一: destroyed()

方法二:beforeRouteLeave(to, from, next) 推荐

所有代码


轮询:polling

1 在data中定义

     data() {
        return {
            polling: ''
        }
    },

2 在methods中定义

     methods: {
      getDateLoop(timeout = 15000) { // timeout可以写死,也可以动态
        console.log('查询'); // 执行语句
        this.polling = setInterval(() => {
          console.log('查询'); // 轮询中,执行语句
        }, timeout)
      },
    },

3 开始轮询

    created() {
      this.getDateLoop(); // 开始轮询
    },

在当前页面不停打印,说明轮询成功

4 终止轮询

方法一: destroyed()

这个方法,反复跳转后会失效(有点奇怪),所以转用方法二

失效原因:开发的网页是SPA-单页面应用,每次页面跳转,都是由路由机制管理,刷新的只有网页内容。(因为这个销毁过程失灵时不灵,所以博主猜测:)页面跳转的时候不一定会销毁这个组件所以这个方法失灵时不灵。

     destroyed() {
       clearInterval(this.polling) // 结束轮询
     },

跳转页面后,停止打印,说明轮询停止

方法二:beforeRouteLeave(to, from, next) 推荐

    beforeRouteLeave(to, from, next){  // 路由跳转前,清除轮询
        next();
        if (this.polling) {
          clearInterval(this.polling);
          this.polling = null;
        }
     },

所有代码

     data() {
        return {
            polling: ''
        }
    },
     methods: {
      getDateLoop(timeout = 15000) { // timeout可以写死,也可以动态
        console.log('查询'); // 执行语句
        this.polling = setInterval(() => {
          console.log('查询'); // 轮询中,执行语句
        }, timeout)
      },
    },
    created() {
      this.getDateLoop(); // 开始轮询
    },
    // destroyed() {
    //   clearInterval(this.polling) // 结束轮询
    // },
    beforeRouteLeave(to, from, next){  // 路由跳转前,清除轮询
        next();
        if (this.polling) {
          clearInterval(this.polling);
          this.polling = null;
        }
     },

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值