学无先后,达者为师

网站首页 Vue 正文

vue项目中轮询状态更改方式(钩子函数)_vue.js

作者:骑上我心爱的小摩托   更新时间: 2022-11-28 Vue

vue项目中轮询状态更改

在实际项目中,对于实时存储改变的数据,如果不是使用websoct,就需要使用到轮询,对于轮询实际是前端设置的定时器,不停存储获取数据并进行更改。

而对于退出该界面后,轮询逻辑依然在定时器的执行中进行,此时需要用到钩子函数判断路由离开状态后,进行清除定时器

 //离开当前页面
beforeRouteLeave(to, from, next) {
    window.clearInterval(this.myInterval);

    //清除定时器
    next();
},

vue轮询方法及清除

<script>
  var Vue = new Vue({
    el: '#app',
    data: {
      timer: null,
    },
    created() {
		this.pollfun()
    },
    methods: {
      //轮询
      pollfun() {
        this.timer = window.setInterval(() => {
          setTimeout(() => {
            this.getDetes()
          }, 0)
        }, 3000)
      },
      //清除轮询
      clearfun() {
        clearInterval(this.timer);
        this.timer = null;
      }
    },
    //离开页面清除
    destroyed() {
      window.clearInterval(this.timer)
    }
  })
</script>

destroyed 是监听页面销毁钩子函数

原文链接:https://blog.csdn.net/cxwtsh123/article/details/80163801

栏目分类
最近更新