方法

data(){
    return {
        intervalId:null
    }
},
methods:{
   // 定时刷新数据函数
    dataRefreh() {
      // 计时器正在进行中,退出函数
      if (this.intervalId != null) {
        return;
      }
      // 计时器为空,操作
      this.intervalId = setInterval(() => {
        console.log("刷新" + new Date());
        this.initData(); //加载数据函数
      }, 5000);
    }, 
    // 停止定时器
    clear() {
      clearInterval(this.intervalId); //清除计时器
      this.intervalId = null; //设置为null
    },
},
created(){
    this.dataRefreh();
},
destroyed(){
    // 在页面销毁后,清除计时器
    this.clear();
}
  • 首先选择数据刷新的时机,在created

  • 声明计时器,与数据刷新函数

  • 在页面销毁的时机(destroyed),关闭计时器等耗时操作


什么时候触发和销毁

created:在这个时期定义的方法都可以使用,可以在这个时期触发页面的定时刷新

mounted:在元素挂载之后去触发

beforeDestroy:在当前页面被销毁的时候清除

在这里插入图片描述

问题:

1. 使用setIntervalthis指向的问题

如果我们直接

this.timer = setInterval(function(){要触发的函数})是会报错的。因为这样的话this的指向为window,但是我们要触发的函数是挂载在vm实例上面的。所以这个时候就是箭头函数发挥用处的时候了。我们可以直接这样写this.timer = setInterval(() => {要触发的函数})

2. 使用moutedbeforeDestory时注意他们是和method平级的

mouted(){
    if(this.timer){
            clearInterval(this.timer)
       } else {
               thjis.timer = setInterval(() => {
                   this.getMigrateDetail();
               },1800000)
       }
},
destroyed(){
    clearImterval(this.timer);
}

这里的getMigrateDetail()是自己定义的一个函数,大家在实现的时候只需要把它替换成自己的函数就ok了

Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐