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