雅涵

个人网站:https://wenyayun.com

导航

每隔10秒刷新页面 vue

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

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

一开始我用的是下面的方法
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秒刷新数据

}

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

第二种方法:

data() {

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

},

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

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}`
}

posted on 2017-04-22 22:22  Mona-雅  阅读(2644)  评论(0编辑  收藏  举报