:::
主內容區域
14-3 後台的 fetch
- fetch 可以在任何元件目錄下執行, asyncData 只能在 page 目錄下執行
- fetch 在 vue 實體產生後才執行(所以可以取得 this) ,也就是在asyncData 之後
- 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> - 若是加入
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> $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>$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>$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>
14-2 後台的 asyncData 