每隔10秒刷新页面 vue

这个问题首先要弄明白js与es6中的this属性到底指的是什么。html

关于VUE中每隔10秒刷新页面的问题,也就是每隔10秒向后台请求数据。es6

一开始我用的是下面的方法
methods: {
  getData(data){
    ....//这是后台接口传过来的数据
  },

  initSetTimeout(today) {//每隔10秒刷新数据,也就是每隔10秒向后台请求一次数据
    setInterval( () => {//es6中这个this指向的是这些方法,若setInterval(function(){ this.getData(today)})中的this指向的真个windows,这样写是会报错的,因此最好用es6来调用getData里的方法
      this.getData(today)
    }, 10000)
  },
},
created() {//页面一进来就得到当前时间,而且调用每隔10秒刷新数据
  const 
    date = new Date(),
    year = date.getFullYear(),
    month = date.getMonth()+1,
    myDate = date.getDate()
    this.today = `${year}/${month < 10 ? '0'+month : month}/${myDate < 10 ? '0'+myDate : myDate}`,
    this.getData(this.today)//input显示当前时间
    this.initSetTimeout(this.today)//调用每隔10秒刷新数据windows

}post

用这种方法后又出现了新bug,就是当选择其余时间的时候,定时器仍是不断的向后台请求,并且请求的数据仍是当天的时间,而不是我所选择时间,每隔10秒后又调回了当天的数据页面。这样确定是不对的啊。this

第二种方法:htm

data() {blog

  flag: true//阻止除今天觉得的时间显示定时器接口

},开发

methods: {
  getData(data){
    ....//这是后台接口传过来的数据
  },
},get

mounted() {//每隔10秒刷新今天的列表数据
  this.getData(this.today)
  setInterval(()=> {
    if (this.date === this.today.replace(/\//g, ''))
    this.getData(this.date)
  }, 10000)
},

created() {//input里填充当前的时间
  let 
    date = new Date(),
    year = date.getFullYear(),
    month = date.getMonth()+1,
    myDate = date.getDate()
    this.today = `${year}/${month < 10 ? '0'+month : month}/${myDate < 10 ? '0'+myDate : myDate}`
}

这样就能够实现每隔10秒向后台请求,就每隔10秒刷新了。

可是,这样写仍是出现了新的bug,那就是点击其余页面时那个定时还在不断的加载,后台开发反应那样很差,其实无论有没有禁止掉,他仍是在不停的请求的,只不过的隐藏了而已。可是后台有须要仍是得作嘛。

第三种方法。

data() {

  flag: true//阻止除今天觉得的时间显示定时器

},

methods: {
  getData(data){
    ....//这是后台接口传过来的数据
  },
},

mounted() {//每隔10秒刷新今天的列表数据
  this.getData(this.today)
  setInterval(()=> {
    if (this.date === this.today.replace(/\//g, '') && location.hash.includes('#/prizeList') )//出现当前页面是就执行
    this.getData(this.date)
  }, 10000)
},

created() {//input里填充当前的时间
  let 
    date = new Date(),
    year = date.getFullYear(),
    month = date.getMonth()+1,
    myDate = date.getDate()
    this.today = `${year}/${month < 10 ? '0'+month : month}/${myDate < 10 ? '0'+myDate : myDate}`
}

转载于:https://www.cnblogs.com/wendy-home-5678/p/6750056.html