:::

14-3 後台的 fetch

  1. fetch 可以在任何元件目錄下執行, asyncData 只能在 page 目錄下執行
  2. fetch 在 vue 實體產生後才執行(所以可以取得 this) ,也就是在asyncData 之後
  3. fetch 無法直接 return,所以傲用 this.變數來指定新值,覆蓋 data 中的值,例如:
    <script>
    import axios from "axios";
    export default {
      // async asyncData() {
      //   const res = await axios.get("http://blog.lces.tn.edu.tw/api.php");
      //   return { res: res.data.data };
      // }
      data() {
        return {
          res: []
        };
      },
      async fetch() {
        this.res = await axios
          .get("http://blog.lces.tn.edu.tw/api.php")
          .then(respon => respon.data.data);
      }
    };
    </script>

     

  4. 若是加入fetchOnServer: false,則會變成在前端執行,如:
    <script>
    import axios from "axios";
    export default {
      data() {
        return {
          res: []
        };
      },
      fetchOnServer: false,
      async fetch() {
        this.res = await axios
          .get("http://blog.lces.tn.edu.tw/api.php")
          .then(respon => respon.data.data);
      }
    };
    </script>

     

  5. $fetchState.pending 可以取得 fetch 是否執行完畢的狀態,例如:
    <template>
      <div class="container">
        <div>
          <Logo />
          <h1 v-if="$fetchState.pending">載入中...</h1>
          <h1 v-if="!$fetchState.pending" class="title">
            校園日誌
          </h1>
          <ul v-if="!$fetchState.pending">
            <li v-for="news in res" key="news.id">{{ news.title }}</li>
          </ul>
        </div>
      </div>
    </template>
    

     

  6. $fetchState.error 可以取得 fetch 是否執行出錯的訊息,例如:
    <template>
      <div class="container">
        <div>
          <Logo />
          <h1 v-if="$fetchState.pending">載入中...</h1>
          <h1 v-if="$fetchState.error">出錯了...{{ $fetchState.error }}</h1>
      </div>
    </template>

     

  7. $fetchState.timestamp 可搭配 keep-alive 使用於activated生命週期中使用(activated生命週期只有有用 keep-alive 時才會有),讓資料可以進行緩存,例如:
    <template>
      <div>
          <Nuxt keep-alive />
      </div>
    </template>

    page/index.vue

    <script>
    import axios from "axios";
    export default {
      data() {
        return {
          res: [],
        };
      },
      activated() {
        // Call fetch again if last fetch more than 30 sec ago
        if (this.$fetchState.timestamp <= Date.now() - 30000) {
          this.$fetch();
        }
      },
      fetchOnServer: false,
      async fetch() {
        this.res = await axios
          .get("http://blog.lces.tn.edu.tw/api.php")
          .then((respon) => respon.data.data);
      },
    };
    </script>
    

     

  8.  

:::

書籍目錄

展開 | 闔起

http%3A%2F%2Fcampus-xoops.tn.edu.tw%2Fmodules%2Ftad_book3%2Fpage.php%3Ftbsn%3D33%26tbdsn%3D1852

計數器

今天: 1708170817081708
昨天: 3438343834383438
總計: 7392037739203773920377392037739203773920377392037