首页  >  问答  >  正文

如何在自定义挂钩内创建 useFetch 的副本?

<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>
P粉928591383P粉928591383417 天前355

全部回复(1)我来回复

  • P粉032900484

    P粉0329004842023-08-29 09:48:02

    useFetch 使用缓存来避免多个相同的请求。

    如果您在选项中设置initialCache: false,则可以禁用缓存,例如

    useFetch(API_PREFIX + url, {
        ...options,
        initialCache: false,
      }
    )
    

    回复
    0
  • 取消回复