数据获取类
| 函数 | 用途 | 响应式 | SSR 传递 | 阻塞导航 |
|---|---|---|---|---|
useFetch | 标准数据获取 | ✅ | ✅ | ✅ 默认 |
useAsyncData | 自定义获取逻辑 | ✅ | ✅ | ✅ 默认 |
useLazyFetch | 非阻塞数据获取 | ✅ | ✅ | ❌ |
useLazyAsyncData | 非阻塞自定义获取 | ✅ | ✅ | ❌ |
$fetch | 纯 HTTP 请求 | ❌ | ❌ | N/A |
createUseFetch | 自定义 useFetch 实例 | ✅ | ✅ | 可配置 |
useFetch
SSR 友好的数据获取组合式函数,最常用的数据获取方式。
ts
const { data, status, error, refresh, clear } = await useFetch('/api/users', {
method: 'GET',
query: { page: 1 },
body: { name: 'Alice' },
headers: {},
baseURL: '',
server: true, // 是否在服务端执行
lazy: false, // 是否阻塞导航
immediate: true, // 是否立即执行
default: () => [], // 默认值
transform: (data) => data, // 数据转换
pick: ['id', 'name'], // 提取字段
watch: [], // 监听源
deep: false, // 深度 ref
dedupe: 'cancel', // 去重策略
timeout: undefined, // 超时时间
getCachedData: (key, nuxtApp) => undefined, // 自定义缓存
})| 返回值 | 类型 | 说明 |
|---|---|---|
data | Ref<T> | 响应数据 |
status | Ref<string> | idle/pending/success/error |
error | Ref<Error> | 错误信息 |
pending | Ref<boolean> | 是否加载中(等价于 status === 'pending') |
refresh | (opts?) => Promise<void> | 刷新数据 |
execute | (opts?) => Promise<void> | refresh 的别名 |
clear | () => void | 清除数据 |
TIP
详见 useFetch 完整教程
useAsyncData
更灵活的异步数据获取,支持自定义获取函数。
ts
const { data, status, error, refresh, clear } = await useAsyncData(
'key', // 必须,缓存键
() => $fetch('/api/users'), // 获取函数
{ server: true, lazy: false } // 选项(与 useFetch 相同)
)与 useFetch 的区别
必须手动指定 key,获取函数可以是任何异步操作(不限于 HTTP 请求)。
TIP
详见 useAsyncData 完整教程
useLazyFetch
非阻塞版 useFetch,页面先显示再获取数据。
ts
const { data, pending, error } = useLazyFetch('/api/users')
// 等价于 useFetch('/api/users', { lazy: true })INFO
️ data 初始为 undefined 需要 default: () => [] 或 pending 处理
TIP
详见 懒加载获取 完整教程
useLazyAsyncData
非阻塞版 useAsyncData。
ts
const { data, pending, error } = useLazyAsyncData('users', () => $fetch('/api/users'))
// 等价于 useAsyncData('users', () => $fetch('/api/users'), { lazy: true })$fetch
基于 ofetch 的 HTTP 请求函数,非响应式。
ts
// GET
const data = await $fetch('/api/users')
// POST
const user = await $fetch('/api/users', {
method: 'POST',
body: { name: 'Alice' },
})
// 错误处理(4xx/5xx 自动抛出 FetchError)
try {
const data = await $fetch('/api/data')
} catch (error) {
if (error instanceof FetchError) {
console.log(error.statusCode)
}
}INFO
️ $fetch 不传递 SSR Payload 页面数据获取请用 useFetch,事件处理用 $fetch
TIP
详见 $fetch 完整教程
createUseFetch(v4.4+)
创建自定义 useFetch 实例,预设默认选项。
ts
// app/composables/useApiFetch.ts
export const useApiFetch = createUseFetch((options) => ({
...options,
baseURL: options.baseURL ?? useRuntimeConfig().public.apiBase,
headers: {
...options.headers,
Authorization: `Bearer ${useCookie('token').value}`,
},
}))
// 使用
const { data } = await useApiFetch('/users')createUseAsyncData(v4.4+)
创建自定义 useAsyncData 实例。
ts
// app/composables/useApiAsyncData.ts
export const useApiAsyncData = createUseAsyncData((options) => ({
...options,
server: false, // 默认不在服务端获取
}))
// 使用
const { data } = await useApiAsyncData('users', () => $fetch('/api/users'))