之前有介紹過 使用 axios 呼叫 API ,
在 Nuxt3 中有內建的方式可以很方便的呼叫 API 並取得回應內容,本篇要介紹的就是 useFetch 。他主要是用在元件載入時直接呼叫 API 使用的,如果是其他時候例如使用者填完表單要送出則是要使用 $fetch
使用 GET 呼叫後的回應內容為:
使用 useFetch ,用 GET 方法呼叫並顯示回應內容:
確認狀態和有回應內容:
萬一沒有 API 可以測試怎麼辦?
延伸閱讀: 使用 Mockoon 快速建立測試用的假 API
參考資料:
Nuxt - Data fetching
Nuxt - useFetch
GitHub - unjs/ofetch
最簡單的使用方式
假設我們有一個 API ,連結為: http://localhost:8888/users/1使用 GET 呼叫後的回應內容為:
{
"id": 1,
"name": "小明"
}
使用 useFetch ,用 GET 方法呼叫並顯示回應內容:
const {data} = await useFetch('http://localhost:8888/users/1');
console.log(`data: ${JSON.stringify(data.value)}`); // data: {"id":1,"name":"小明"}
確認狀態和有回應內容:
const {data, status} = await useFetch('http://localhost:8888/users/1');
if (status.value === 'success' && data.value) { // 狀態是成功並且有資料
console.log('成功');
console.log(`data: ${data.value.id}, ${data.value.name}`); // data: 1, 小明
}
萬一沒有 API 可以測試怎麼辦?
延伸閱讀: 使用 Mockoon 快速建立測試用的假 API
常用參數
可以成功取得內容後信心大增,那來看看有那些常用參數吧:
const url = 'http://localhost:8888/users/1';
const {
data, // 回應內容
pending, // 是否正在請求中
error, // 錯誤物件
refresh, // 重新發送請求
status // 資料請求狀態字串: idle, pending, success, error
} = await useFetch(url, {
method: 'POST', // GET, POST, PUT, PATCH, DELETE
headers: {}, // 自訂標頭,範例: { 'Content-Type': 'application/json' }
query: {}, // 請求參數,範例: { id: 1 }
body: {}, // 請求內容(GET 不能有 body),範例: { id: 1, name: '小明' }
watch: [], // 監聽資料變化,變化時重新發送請求(後面有使用示範)
});
TypeScript 定義資料格式
如果是使用 TypeScript ,並且知道資料回傳的格式,那我們就可以事先定義資料格式,方便後續處理時 IDE 可以自動提示資料型別:
const url = 'http://localhost:8888/users/1';
const {data, pending, error, refresh} = await useFetch<{ id: number; name: string }>(url, {
method: 'GET',
});
if (data.value) {
console.log(`data: ${data.value.id}, ${data.value.name}`); // data: 1, 小明
}
攔截器 - 使用非同步方式取得回應
const url = 'http://localhost:8888/users/1';
const {data, pending, error, refresh} = await useFetch(url, {
method: 'GET',
onRequest({request, options}) {
console.log(`發送請求`);
},
onRequestError({request, options, error}) {
console.log(`請求出現錯誤: ${error}`);
},
onResponse({request, response, options}) {
console.log(`成功取得回應: ${JSON.stringify(response)}`);
},
onResponseError({request, response, options}) {
console.log(`取得回應失敗`);
}
})
自動重送請求
在 Google 搜尋時是不是一打字就會出現建議內容?假設我們有個 API 用來發送使用者輸入的內容,然後取得建議內容回應,就可以使用 watch 的這個功能來達成:
<template>
<input type="text" v-model="inputVal" placeholder="請輸入文字">
<div>count: {{ count }}</div>
</template>
<script lang="ts" setup>
const inputVal = ref<string>('');
const count = ref<number>(0);
const url = 'http://localhost:8888/users/1';
const {data} = await useFetch(url, {
method: 'GET',
watch: [inputVal], // 監聽資料變化,變化時重新發送請求
onResponse({request, response, options}) {
count.value++;
},
});
</script>
參考資料:
Nuxt - Data fetching
Nuxt - useFetch
GitHub - unjs/ofetch
留言
張貼留言
如果有任何問題、建議、想說的話或文章題目推薦,都歡迎留言或來信: a@ruyut.com