vue 缓存过期时间,每天零点发送请求


用别人的轮子真好啊,拿来就用,没有的话就只有自己写了

这样一个业务,每天零点只发送一次请求,

实现思路

  1. 请求中缓存当天日期。

  2. 进入页面获取当天日期,获取缓存中的日期,判断:如果当天日期大于缓存日期  则表示缓存过期,重新发送请求。

第一步,执行mouted获取数据。

mounted() {
  // 获取到缓存数据
  let ckInfo = JSON.parse(localStorage.getItem('ckInfo'))||false;
  
  if (ckInfo) {
    // 获取到缓存日期
    let oldTimer = ckInfo.timer;
    // 获取当前日期,并转成整数。
    let timer = this.conversionTime(new Date());

    // 如果当前日期大于 缓存中的日期, 重新发送请求。
    if (timer>oldTimer) {
      this.getUserInfo();
    } else {
      this.clockInInfo = ckInfo;
    }
  } else {
    this.getUserInfo();
  }
},

第二步,methods里面添加下面两个方法。

getUserInfo() {
  axios.get(API_MEMBER_GRADE,{}, true).then(res => {
    if (res.returnCode == 200) {
      let ckInfo = res.data.clockInInfo;
      // 缓存过期时间 
      ckInfo.timer = this.conversionTime(new Date());

      // 缓存请求数据,后面就走缓存,今天结束就清空一次缓存。
      localStorage.setItem('ckInfo',JSON.stringify(ckInfo));
    } else {
      Toast(res.msg);
    }
  })
},
// 获取时间转成整数
conversionTime (time) {
  // let dateClose = new Date();
  let dateClose = time;
  let seperator1Close = "-";
  let yearClose = dateClose.getFullYear();
  let monthClose = dateClose.getMonth() + 1;
  let strDateClose = dateClose.getDate();
  if (monthClose >= 1 && monthClose <= 9) {
      monthClose = "0" + monthClose;
  }
  if (strDateClose >= 0 && strDateClose <= 9) {
      strDateClose = "0" + strDateClose;
  }
  let currentdateClose = Number((yearClose + seperator1Close + monthClose + seperator1Close + strDateClose).replace(/-/g, ''));
  // console.log(currentdateClose,'currentdateClose');
  return currentdateClose;
},

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM