52
Vue 3 學習之旅
高級組合式函數
Day 52: 範例:useFetch 資料擷取
·6 分鐘閱讀·資料擷取
摘要
useFetch 是一個用於處理非同步資料獲取的組合式函數。它封裝了請求的載入狀態、錯誤狀態以及最終獲取的資料。
定義與說明
這個函數通常接收一個 URL 作為參數。它內部會維護三個響應式狀態:data
(儲存成功獲取的資料)、error
(儲存錯誤訊息)和 isLoading
(表示是否正在載入中)。它會立即發起 fetch 請求,並根據請求的結果更新這些狀態。
實作範例
useFetch 範例
// composables/useFetch.js
import { ref, toValue } from 'vue';
export function useFetch(url) {
const data = ref(null);
const error = ref(null);
const isLoading = ref(true);
fetch(toValue(url))
.then(res => res.json())
.then(json => data.value = json)
.catch(err => error.value = err)
.finally(() => isLoading.value = false);
return { data, error, isLoading };
}
<!-- ComponentUsingFetch.vue -->
<script setup>
import { useFetch } from './composables/useFetch.js';
const { data, error, isLoading } = useFetch('https://api.example.com/data');
</script>
<template>
<div v-if="isLoading">載入中...</div>
<div v-else-if="error">錯誤: {{ error.message }}</div>
<pre v-else>{{ data }}</pre>
</template>
結論
useFetch 將複雜的非同步資料獲取流程(包括載入和錯誤處理)簡化為一個乾淨、可複用的函數,讓元件可以專注於如何展示資料,而不是如何獲取資料。
useFetch 非同步 資料獲取