useFetch
此可组合项提供了一个便捷的 useAsyncData
和 $fetch
封装器。它会根据 URL 和获取选项自动生成键,根据服务器路由为请求 URL 提供类型提示,并推断 API 响应类型。
¥This composable provides a convenient wrapper around useAsyncData
and $fetch
.
It automatically generates a key based on URL and fetch options, provides type hints for request url based on server routes, and infers API response type.
useFetch
是一个可组合函数,旨在直接在设置函数、插件或路由中间件中调用。它返回响应式可组合函数,并负责将响应添加到 Nuxt 负载中,以便它们可以从服务器传递到客户端,而无需在页面刷新时在客户端重新获取数据。用法
¥Usage
<script setup lang="ts">
const { data, status, error, refresh, clear } = await useFetch('/api/modules', {
pick: ['title']
})
</script>
data
、status
和 error
是 Vue 引用,在 <script setup>
中使用时,应通过 .value
访问,而 refresh
/execute
和 clear
是普通函数。使用 query
选项,你可以将搜索参数添加到查询中。此选项扩展自 unjs/ofetch,并使用 unjs/ufo 创建 URL。对象会自动字符串化。
¥Using the query
option, you can add search parameters to your query. This option is extended from unjs/ofetch and is using unjs/ufo to create the URL. Objects are automatically stringified.
const param1 = ref('value1')
const { data, status, error, refresh } = await useFetch('/api/modules', {
query: { param1, param2: 'value2' }
})
上述示例生成了 https://api.nuxt.com/modules?param1=value1¶m2=value2
。
¥The above example results in https://api.nuxt.com/modules?param1=value1¶m2=value2
.
你还可以使用 interceptors:
¥You can also use interceptors:
const { data, status, error, refresh, clear } = await useFetch('/api/auth/login', {
onRequest({ request, options }) {
// Set the request headers
// note that this relies on ofetch >= 1.4.0 - you may need to refresh your lockfile
options.headers.set('Authorization', '...')
},
onRequestError({ request, options, error }) {
// Handle the request errors
},
onResponse({ request, response, options }) {
// Process the response data
localStorage.setItem('token', response._data.token)
},
onResponseError({ request, response, options }) {
// Handle the response errors
}
})
响应式键和共享状态
¥Reactive Keys and Shared State
你可以使用计算引用或纯文本引用作为 URL,从而允许动态数据获取,并在 URL 更改时自动更新:
¥You can use a computed ref or a plain ref as the URL, allowing for dynamic data fetching that automatically updates when the URL changes:
<script setup lang="ts">
const route = useRoute()
const id = computed(() => route.params.id)
// When the route changes and id updates, the data will be automatically refetched
const { data: post } = await useFetch(() => `/api/posts/${id.value}`)
</script>
在多个组件中使用具有相同 URL 和选项的 useFetch
时,它们将共享相同的 data
、error
和 status
引用。这确保了组件间的一致性。
¥When using useFetch
with the same URL and options in multiple components, they will share the same data
, error
and status
refs. This ensures consistency across components.
useFetch
是一个由编译器转换的保留函数名,因此你不应将自己的函数命名为 useFetch
。¥useFetch
is a reserved function name transformed by the compiler, so you should not name your own function useFetch
.useFetch
解构的 data
变量返回字符串而不是 JSON 解析对象,请确保你的组件不包含像 import { useFetch } from '@vueuse/core
这样的导入语句。¥If you encounter the data
variable destructured from a useFetch
returns a string and not a JSON parsed object then make sure your component doesn't include an import statement like import { useFetch } from '@vueuse/core
.参数
¥Params
URL
:要获取的 URL。Options
(扩展 unjs/ofetch 选项和 AsyncDataOptions):
computed
或 ref
值。这些值将被监视,并且如果更新,将自动使用任何新值发出新请求。Options
(来自useAsyncData
):key
:一个唯一键,用于确保数据提取能够在请求之间正确去重。如果未提供,则会根据 URL 和提取选项自动生成。server
:是否在服务器上获取数据(默认为true
)lazy
:是否在加载路由后解析异步函数,而不是阻止客户端导航(默认为false
)immediate
:设置为false
时,将阻止请求立即触发。(默认为true
)default
:一个工厂函数,用于在异步函数解析之前设置data
的默认值 - 与lazy: true
或immediate: false
选项配合使用非常有用transform
:一个函数,用于在解析后更改handler
函数的结果getCachedData
:提供一个返回缓存数据的函数。null
或undefined
的返回值将触发抓取。默认情况下:const getDefaultCachedData = (key, nuxtApp, ctx) => nuxtApp.isHydrating ? nuxtApp.payload.data[key] : nuxtApp.static.data[key]
仅在启用nuxt.config
的experimental.payloadExtraction
时缓存数据。pick
:仅从handler
函数结果中选取此数组中的指定键。watch
:监视响应式源数组,并在它们发生变化时自动刷新获取结果。默认情况下,获取选项和 URL 会被监视。你可以使用watch: false
完全忽略响应式源。与immediate: false
结合使用,可实现完全手动的useFetch
。(你可以选择 查看此处的示例 或使用watch
。)deep
:在深度引用对象中返回数据。默认情况下,false
会将数据返回到浅引用对象中以提高性能。dedupe
:避免一次多次获取相同的键(默认为cancel
)。可能的选项:cancel
- 发出新请求时取消现有请求defer
- 如果有待处理的请求,则根本不发出新请求。
url
参数,或者如果你提供函数作为 options
参数的实参,那么 useFetch
调用将不会匹配代码库中其他位置的 useFetch
调用,即使选项看起来相同。如果你希望强制匹配,你可以在 options
中提供自己的密钥。useFetch
调用带有自签名证书的(外部)HTTPS URL,则需要在你的环境中设置 NODE_TLS_REJECT_UNAUTHORIZED=0
。返回值
¥Return Values
data
:传入的异步函数的结果。refresh
/execute
:一个函数,用于刷新handler
函数返回的数据。error
:如果数据获取失败,则返回一个错误对象。status
:一个字符串,指示数据请求的状态:idle
:当请求尚未启动时,例如:- 当
execute
尚未被调用且{ immediate: false }
已设置时 - 当在服务器上渲染 HTML 且
{ server: false }
已设置时
- 当
pending
:请求正在进行中success
:请求已成功完成error
:请求失败
clear
:一个函数,用于将data
设置为undefined
,将error
设置为null
,将status
设置为'idle'
,并将当前待处理的请求标记为已取消。
默认情况下,Nuxt 会等待 refresh
完成后才能再次执行。
¥By default, Nuxt waits until a refresh
is finished before it can be executed again.
server: false
),则在 hydration 完成之前,数据将不会被获取。这意味着,即使你在客户端等待 useFetch
,data
在 <script setup>
中仍将保持为 null。类型
¥Type
function useFetch<DataT, ErrorT>(
url: string | Request | Ref<string | Request> | (() => string | Request),
options?: UseFetchOptions<DataT>
): Promise<AsyncData<DataT, ErrorT>>
type UseFetchOptions<DataT> = {
key?: string
method?: string
query?: SearchParams
params?: SearchParams
body?: RequestInit['body'] | Record<string, any>
headers?: Record<string, string> | [key: string, value: string][] | Headers
baseURL?: string
server?: boolean
lazy?: boolean
immediate?: boolean
getCachedData?: (key: string, nuxtApp: NuxtApp, ctx: AsyncDataRequestContext) => DataT | undefined
deep?: boolean
dedupe?: 'cancel' | 'defer'
default?: () => DataT
transform?: (input: DataT) => DataT | Promise<DataT>
pick?: string[]
watch?: WatchSource[] | false
}
type AsyncDataRequestContext = {
/** The reason for this data request */
cause: 'initial' | 'refresh:manual' | 'refresh:hook' | 'watch'
}
type AsyncData<DataT, ErrorT> = {
data: Ref<DataT | null>
refresh: (opts?: AsyncDataExecuteOptions) => Promise<void>
execute: (opts?: AsyncDataExecuteOptions) => Promise<void>
clear: () => void
error: Ref<ErrorT | null>
status: Ref<AsyncDataRequestStatus>
}
interface AsyncDataExecuteOptions {
dedupe?: 'cancel' | 'defer'
}
type AsyncDataRequestStatus = 'idle' | 'pending' | 'success' | 'error'