如何在自訂掛鉤內建立 useFetch 的副本?
P粉928591383
2023-08-28 15:24:54
<p>我正在嘗試創建一個可多次使用的鉤子,但我得到的行為不是我期望的</p>
<p>/composables/fetch.ts</p>
<pre class="brush:js;toolbar:false;">export const useFetchWithErrorHandler = async (url: string, options?: FetchOptions) => {
const route = useRoute();
const { API_BASE_URL, API_PREFIX } = useRuntimeConfig();
console.log(url, options);
return new Promise(async (resolve, reject) => {
const response = await useFetch(API_PREFIX url, {
...options,
baseURL: API_BASE_URL,
initialCache: false,
async onResponse({ request, response, options }) {
console.log('[fetch response]', response);
},
async onResponseError({ request, response, options }) {
console.log('[fetch response error]');
},
});
resolve(response);
});
</pre>
<p>只觸發第一個請求</p>
<pre class="brush:js;toolbar:false;">const { data: response } = await useFetchWithErrorHandler(`page-1`, {
pick: ['data'],
});
const { data: response } = await useFetchWithErrorHandler(`page-2`, {
pick: ['data'],
});
</pre></p>
useFetch
使用快取來避免多個相同的請求。如果您在選項中設定
initialCache: false
,則可以停用緩存,例如