每分鐘通知 API,無需依賴用戶重新載入
P粉937382230
P粉937382230 2024-03-31 14:34:11
0
1
344

這就是我現在所擁有的。 在我的 Mount() 上,我有 fetchCoins(),但這使得每當用戶刷新時,就會呼叫 API

我正在嘗試呼叫API,資料儲存在本地儲存中,然後每分鐘獲取一次資料

methods: {
    async fetchCoins() {
      const response = await fetch("https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=false&price_change_percentage=1h");
      const data = await response.json();
      this.coins = this.coins.concat(data);
    },

    setData() {
      localStorage.setItem('coin-info', JSON.stringify(this.coins))
    },

    getData() {
      let get = localStorage.getItem('coin-info', []);
      this.coins = JSON.parse(get);
      console.log(this.coins);

      setInterval(() => {
        this.fetchCoins()
      }, 60000);
    },
}

P粉937382230
P粉937382230

全部回覆(1)
P粉493534105

您需要在 localStorage 中追蹤上次取得發生的日期。這是一個範例實作:

   scheduleNextFetchCoins() {
       const lastFetch = new Date(localStorage.getItem('coin-info-last-fetch'));
       
       const timeDelta = Date.now() - lastFetch.valueOf();
       const nextCall = Math.max(60000 - timeDelta, 0);
       
       setTimeout(() => {
           this.fetchCoins();
           localStorage.setItem('coin-info-last-fetch', new Date());

           this.scheduleNextFetchCoins();
       }, nextCall)
   }

您需要在該函數的 mounted 函數中變更對 this.fetchCoins() 的呼叫。

但請記住,關於此程式碼片段有一些警告(超出了問題的範圍):

  • setTimeoutsetInterval 並不是完全準確的時間函數。它們可能會延遲幾毫秒。如果您擔心這種錯誤,請查看其他一些提出解決方案的問題,例如這個
  • 此程式碼片段僅適用於元件的單一實例。建立多個元件將導致寫入 coin-info-last-fetch 的競爭條件。
  • 沒有什麼可以阻止獲取循環,即使元件被銷毀也是如此。您需要將 setTimeout 傳回的逾時 ID 儲存在元件的資料中,以便最終能夠清除它。
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!