Lzh on GitHub

数据获取

Nuxt 提供了 composables 来处理应用程序中的数据获取。

Nuxt 自带两个 composables 和一个内置库,用于在浏览器或服务器环境中执行数据获取:useFetchuseAsyncData$fetch

简而言之:

  • $fetch 是发起网络请求的最简单方式。
  • useFetch$fetch 的包装器,它仅在 通用渲染 中获取一次数据。
  • useAsyncData 类似于 useFetch,但提供更细粒度的控制。

useFetchuseAsyncData 都共享一组通用的选项和模式,我们将在最后几节中详细介绍。

useFetchuseAsyncData 的必要性

Nuxt 是一个可以在服务器和客户端环境中运行同构(或通用)代码的框架。如果在 Vue 组件的 setup 函数中使用 $fetch 函数 执行数据获取,这可能会导致数据被获取两次,一次在服务器端(用于渲染 HTML),另一次在客户端(当 HTML 水合时)。这可能会导致水合(hydration)问题,增加交互时间并导致不可预测的行为。

useFetchuseAsyncData composables 通过确保如果在服务器端进行 API 调用,数据会转发到客户端的 payload 中来解决这个问题。

payload 是一个可以通过 useNuxtApp().payload 访问的 JavaScript 对象。它在客户端用于避免在浏览器 水合期间 执行代码时重新获取相同的数据。

使用 Nuxt DevToolsPayload 选项卡中检查此数据。
app.vue
<script setup lang="ts">
const { data } = await useFetch('/api/data')

async function handleFormSubmit() {
  const res = await $fetch('/api/submit', {
    method: 'POST',
    body: {
      // My form data
    }
  })
}
</script>

<template>
  <div v-if="data == null">
    No data
  </div>
  <div v-else>
    <form @submit="handleFormSubmit">
      <!-- form input tags -->
    </form>
  </div>
</template>

在上面的示例中,useFetch 将确保请求发生在服务器端并正确转发到浏览器。$fetch 没有这种机制,当请求仅从浏览器发出时,它是更好的选择。

Suspense

Nuxt 在底层使用 Vue 的 <Suspense> 组件,以防止在每个异步数据都可用于视图之前进行导航。数据获取 composables 可以帮助您利用此功能,并根据每次调用的情况使用最适合的方式。

您可以添加 <NuxtLoadingIndicator> 以在页面导航之间添加进度条。

$fetch

Nuxt 包含了 ofetch 库,并在您的应用程序中全局自动导入为 $fetch 别名。

pages/todos.vue
<script setup lang="ts">
async function addTodo() {
  const todo = await $fetch('/api/todos', {
    method: 'POST',
    body: {
      // My todo data
    }
  })
}
</script>
请注意,仅使用 $fetch 不会提供 网络调用去重和阻止导航
建议将 $fetch 用于客户端交互(基于事件)或在获取初始组件数据时与 useAsyncData 结合使用。
阅读更多关于 $fetch 的信息。

将客户端 Headers 传递给 API

在服务器上调用 useFetch 时,Nuxt 将使用 useRequestFetch 代理客户端 headers 和 cookies(不打算转发的 headers 除外,例如 host)。

<script setup lang="ts">
const { data } = await useFetch('/api/echo');
</script>
// /api/echo.ts
export default defineEventHandler(event => parseCookies(event))

或者,下面的示例演示了如何使用 useRequestHeaders 从服务器端请求(源自客户端)访问 cookie 并将其发送到 API。通过使用同构的 $fetch 调用,我们确保 API 端点可以访问用户浏览器最初发送的相同的 cookie header。此方法仅在未使用 useFetch 时才需要。

<script setup lang="ts">
const headers = useRequestHeaders(['cookie'])

async function getCurrentUser() {
  return await $fetch('/api/me', { headers })
}
</script>
您还可以使用 useRequestFetch 自动代理 headers 到调用。
在将 headers 代理到外部 API 之前要非常小心,只包含您需要的 headers。并非所有 headers 都可以安全地绕过,并且可能会引入不必要的行为。以下是不应代理的常见 headers 列表:
  • host, accept
  • content-length, content-md5, content-type
  • x-forwarded-host, x-forwarded-port, x-forwarded-proto
  • cf-connecting-ip, cf-ray

useFetch

useFetch composable 在底层使用 $fetch 在 setup 函数中进行 SSR 安全的网络调用。

app.vue
<script setup lang="ts">
const { data: count } = await useFetch('/api/count')
</script>

<template>
  <p>Page visits: {{ count }}</p>
</template>

这个 composable 是 useAsyncData composable 和 $fetch 工具的包装器。

Read more in Docs > API > Composables > Use Fetch.

useAsyncData

useAsyncData composable 负责包装异步逻辑并在解析后返回结果。

useFetch(url) 几乎等同于 useAsyncData(url, () => event.$fetch(url))
这是最常见用例的开发者体验糖。(您可以在 useRequestFetch 中找到更多关于 event.fetch 的信息。)

在某些情况下,使用 useFetch composable 不合适,例如当 CMS 或第三方提供他们自己的查询层时。在这种情况下,您可以使用 useAsyncData 来包装您的调用,并仍然保留 composable 提供的优势。

pages/users.vue
<script setup lang="ts">
const { data, error } = await useAsyncData('users', () => myGetFunction('users'))

// This is also possible:
const { data, error } = await useAsyncData(() => myGetFunction('users'))
</script>
useAsyncData 的第一个参数是一个唯一的键,用于缓存第二个参数(查询函数)的响应。可以直接传递查询函数来忽略此键,键将自动生成。

由于自动生成的键仅考虑调用 useAsyncData 的文件和行,因此建议始终创建自己的键以避免不必要的行为,例如当您创建自己的包装 useAsyncData 的自定义 composable 时。

设置键对于使用 useNuxtData 在组件之间共享相同数据或 刷新特定数据 很有用。
pages/users/[id].vue
<script setup lang="ts">
const { id } = useRoute().params

const { data, error } = await useAsyncData(`user:${id}`, () => {
  return myGetFunction('users', { id })
})
</script>

useAsyncData composable 是包装和等待多个 $fetch 请求完成,然后处理结果的好方法。

<script setup lang="ts">
const { data: discounts, status } = await useAsyncData('cart-discount', async () => {
  const [coupons, offers] = await Promise.all([
    $fetch('/cart/coupons'),
    $fetch('/cart/offers')
  ])

  return { coupons, offers }
})
// discounts.value.coupons
// discounts.value.offers
</script>
useAsyncData 用于获取和缓存数据,而不是触发副作用(例如调用 Pinia actions),因为这可能会导致意外行为,例如使用 nullish 值重复执行。如果需要触发副作用,请使用 callOnce 工具来执行此操作。
<script setup lang="ts">
const offersStore = useOffersStore()

// you can't do this
await useAsyncData(() => offersStore.getOffer(route.params.slug))
</script>
阅读更多关于 useAsyncData 的信息。

返回值

useFetchuseAsyncData 具有如下相同的返回值。

  • data: 传入的异步函数的结果。
  • refresh/execute: 一个函数,可用于刷新 handler 函数返回的数据。
  • clear: 一个函数,可用于将 data 设置为 undefined,将 error 设置为 null,将 status 设置为 idle,并将任何当前挂起的请求标记为已取消。
  • error: 如果数据获取失败,则为错误对象。
  • status: 一个字符串,指示数据请求的状态 ("idle", "pending", "success", "error")。
dataerrorstatus 是 Vue refs,在 <script setup> 中可以使用 .value 访问。

默认情况下,Nuxt 会等待 refresh 完成后才能再次执行。

如果您没有在服务器端获取数据(例如,使用 server: false),那么在水合完成之前将 不会 获取数据。这意味着即使您在客户端等待 useFetchdata<script setup> 中仍将为 null。

选项

useAsyncDatauseFetch 返回相同的对象类型,并在其最后一个参数中接受一组通用的选项。它们可以帮助您控制 composables 的行为,例如阻止导航、缓存或执行。

Lazy

默认情况下,数据获取 composables 会在使用 Vue 的 Suspense 导航到新页面之前等待其异步函数的解析。可以使用 lazy 选项在客户端导航中忽略此功能。在这种情况下,您必须使用 status 值手动处理加载状态。

app.vue
<script setup lang="ts">
const { status, data: posts } = useFetch('/api/posts', {
  lazy: true
})
</script>

<template>
  <!-- you will need to handle a loading state -->
  <div v-if="status === 'pending'">
    Loading ...
  </div>
  <div v-else>
    <div v-for="post in posts">
      <!-- do something -->
    </div>
  </div>
</template>

或者,您可以使用 useLazyFetchuseLazyAsyncData 作为执行相同操作的便捷方法。

<script setup lang="ts">
const { status, data: posts } = useLazyFetch('/api/posts')
</script>
Read more about useLazyFetch.
Read more about useLazyAsyncData.

仅客户端获取

默认情况下,数据获取 composables 将在客户端和服务器环境中执行其异步函数。将 server 选项设置为 false 以仅在客户端执行调用。在初始加载时,在水合完成之前不会获取数据,因此您必须处理挂起状态,但在随后的客户端导航中,数据将在加载页面之前等待。

lazy 选项结合使用,这对于首次渲染不需要的数据(例如,非 SEO 敏感数据)非常有用。

/* This call is performed before hydration */
const articles = await useFetch('/api/article')

/* This call will only be performed on the client */
const { status, data: comments } = useFetch('/api/comments', {
  lazy: true,
  server: false
})

useFetch composable 旨在在 setup 方法中调用或直接在生命周期钩子中函数的顶层调用,否则您应该使用 $fetch method 方法。

最小化 payload 大小

pick 选项通过仅选择您希望从 composables 返回的字段,帮助您最小化存储在 HTML 文档中的 payload 大小。

<script setup lang="ts">
/* only pick the fields used in your template */
const { data: mountain } = await useFetch('/api/mountains/everest', {
  pick: ['title', 'description']
})
</script>

<template>
  <h1>{{ mountain.title }}</h1>
  <p>{{ mountain.description }}</p>
</template>

如果需要更多控制或遍历多个对象,可以使用 transform 函数来更改查询结果。

const { data: mountains } = await useFetch('/api/mountains', {
  transform: (mountains) => {
    return mountains.map(mountain => ({ title: mountain.title, description: mountain.description }))
  }
})
picktransform 都不会阻止最初获取不需要的数据。但是,它们会阻止不需要的数据添加到从服务器传输到客户端的 payload 中。

缓存和重新获取

Keys

useFetchuseAsyncData 使用键来防止重新获取相同的数据。

  • useFetch 使用提供的 URL 作为键。或者,可以在作为最后一个参数传递的 options 对象中提供 key 值。
  • useAsyncData 如果第一个参数是字符串,则将其用作键。如果第一个参数是执行查询的处理函数,则将为您生成一个对于 useAsyncData 实例的文件名和行号唯一的键。
要按键获取缓存的数据,可以使用 useNuxtData。在 Nuxt 3 中,useNuxtData 支持跨组件共享数据。useNuxtData(key) 通过唯一 Key 访问由 useAsyncDatauseFetch 缓存的数据。当源数据(通过 useFetch 等)刷新时,所有依赖同一 KeyuseNuxtData 返回的 data 会自动更新。

共享状态和选项一致性

当多个组件使用相同的键与 useAsyncDatauseFetch 时,它们将共享相同的 dataerrorstatus refs。这确保了组件之间的一致性,但要求某些选项保持一致。

以下选项对于具有相同键的所有调用 必须保持一致

  • handler 函数
  • deep 选项
  • transform 函数
  • pick 数组
  • getCachedData 函数
  • default
// ❌ This will trigger a development warning
const { data: users1 } = useAsyncData('users', () => $fetch('/api/users'), { deep: false })
const { data: users2 } = useAsyncData('users', () => $fetch('/api/users'), { deep: true })

以下选项 可以安全地不同 而不会触发警告:

  • server
  • lazy
  • immediate
  • dedupe
  • watch
// ✅ This is allowed
const { data: users1 } = useAsyncData('users', () => $fetch('/api/users'), { immediate: true })
const { data: users2 } = useAsyncData('users', () => $fetch('/api/users'), { immediate: false })

如果您需要独立的实例,请使用不同的键:

// These are completely independent instances
const { data: users1 } = useAsyncData('users-1', () => $fetch('/api/users'))
const { data: users2 } = useAsyncData('users-2', () => $fetch('/api/users'))

响应式键

您可以使用计算 ref、普通 ref 或 getter 函数作为键,从而实现动态数据获取,这些数据在依赖项更改时会自动更新:

// Using a computed property as a key
const userId = ref('123')
const { data: user } = useAsyncData(
  computed(() => `user-${userId.value}`),
  () => fetchUser(userId.value)
)

// When userId changes, the data will be automatically refetched
// and the old data will be cleaned up if no other components use it
userId.value = '456'

刷新和执行

如果您想手动获取或刷新数据,请使用 composables 提供的 executerefresh 函数。

<script setup lang="ts">
const { data, error, execute, refresh } = await useFetch('/api/users')
</script>

<template>
  <div>
    <p>{{ data }}</p>
    <button @click="() => refresh()">Refresh data</button>
  </div>
</template>

execute 函数是 refresh 的别名,功能完全相同,但在需要 延迟执行 时,使用 execute 更符合语义。

要全局重新获取或使缓存数据失效,请参阅 clearNuxtDatarefreshNuxtData

清除

如果你想清除提供的数据,无论出于什么原因,而不需要知道传递给 clearNuxtData 的具体键,可以使用组合式 API 提供的 clear 函数。

<script setup lang="ts">
const { data, clear } = await useFetch('/api/users')

const route = useRoute()
watch(() => route.path, (path) => {
  if (path === '/') clear()
})
</script>

监听

要使您的获取函数在应用程序中其他响应式值每次更改时重新运行,请使用 watch 选项。您可以将其用于一个或多个 可观察 的元素。

<script setup lang="ts">
const id = ref(1)

const { data, error, refresh } = await useFetch('/api/users', {
  /* Changing the id will trigger a refetch */
  watch: [id]
})
</script>

请注意,观察响应式值不会改变获取的 URL。例如,这将始终获取用户的初始 ID,因为 URL 是在函数调用时构建的。

<script setup lang="ts">
const id = ref(1)

const { data, error, refresh } = await useFetch(`/api/users/${id.value}`, {
  watch: [id]
})
</script>

如果需要根据响应式值更改 URL,您可能需要使用 计算 URL 来代替。

计算 URL

有时您可能需要从响应式值计算 URL,并在这些值每次更改时刷新数据。与其自己处理,不如将每个参数附加为响应式值。Nuxt 将自动使用响应式值,并在每次更改时重新获取。

<script setup lang="ts">
const id = ref(null)

const { data, status } = useLazyFetch('/api/user', {
  query: {
    user_id: id
  }
})
</script>

对于更复杂的 URL 构建,您可以使用回调作为返回 URL 字符串的 计算 getter

每次依赖项变化时,数据将使用新构建的 URL 进行获取。将此与 not-immediate 结合使用,你可以等到响应式元素发生变化后再进行获取。

<script setup lang="ts">
const id = ref(null)

const { data, status } = useLazyFetch(() => `/api/users/${id.value}`, {
  immediate: false
})

const pending = computed(() => status.value === 'pending');
</script>

<template>
  <div>
    <!-- disable the input while fetching -->
    <input v-model="id" type="number" :disabled="pending"/>

    <div v-if="status === 'idle'">
      Type an user ID
    </div>

    <div v-else-if="pending">
      Loading ...
    </div>

    <div v-else>
      {{ data }}
    </div>
  </div>
</template>

如果需要在其他响应式值更改时强制刷新,您还可以 监听其他值

非立即

useFetch composable 在被调用时会立即开始获取数据。您可以通过设置 immediate: false 来阻止这种情况,例如,等待用户交互。

这样,您将需要 status 来处理获取生命周期,以及 execute 来启动数据获取。

<script setup lang="ts">
const { data, error, execute, status } = await useLazyFetch('/api/comments', {
  immediate: false
})
</script>

<template>
  <div v-if="status === 'idle'">
    <button @click="execute">Get data</button>
  </div>

  <div v-else-if="status === 'pending'">
    Loading comments...
  </div>

  <div v-else>
    {{ data }}
  </div>
</template>

为了更精细的控制,status 变量可以是:

  • idle:获取尚未开始
  • pending:获取已开始但尚未完成
  • error:获取失败
  • success:获取成功完成

传递 Headers 和 Cookies

当我们在浏览器中调用 $fetch 时,用户的 headers(如 cookie)将直接发送到 API。

通常,在服务器端渲染期间,出于安全考虑,$fetch 不会包含用户的浏览器 cookies,也不会传递来自 fetch 响应的 cookies。

但是,当在服务器上使用相对 URL 调用 useFetch 时,Nuxt 将使用 useRequestFetch 代理 headers 和 cookies(不打算转发的 headers 除外,例如 host)。

在 SSR 响应中传递来自服务器端 API 调用的 Cookies

如果您想在另一个方向(从内部请求返回到客户端)传递/代理 cookies,您需要自己处理。

composables/fetch.ts
import { appendResponseHeader } from 'h3'
import type { H3Event } from 'h3'

export const fetchWithCookie = async (event: H3Event, url: string) => {
  /* Get the response from the server endpoint */
  const res = await $fetch.raw(url)
  /* Get the cookies from the response */
  const cookies = res.headers.getSetCookie()
  /* Attach each cookie to our incoming Request */
  for (const cookie of cookies) {
    appendResponseHeader(event, 'set-cookie', cookie)
  }
  /* Return the data of the response */
  return res._data
}
<script setup lang="ts">
// This composable will automatically pass cookies to the client
const event = useRequestEvent()

const { data: result } = await useAsyncData(() => fetchWithCookie(event!, '/api/with-cookie'))

onMounted(() => console.log(document.cookie))
</script>

Options API 支持

Nuxt 提供了一种在 Options API 中执行 asyncData 获取的方法。您必须将组件定义包装在 defineNuxtComponent 中才能使其工作。

<script>
export default defineNuxtComponent({
  /* Use the fetchKey option to provide a unique key */
  fetchKey: 'hello',
  async asyncData () {
    return {
      hello: await $fetch('/api/hello')
    }
  }
})
</script>
建议在 Nuxt 中使用 <script setup><script setup lang="ts"> 来声明 Vue 组件。
注意区分 defineNuxtComponentdefineComponent 定义组件。
Read more in Docs > API > Utils > Define Nuxt Component.

将数据从服务器序列化到客户端

当使用 useAsyncDatauseLazyAsyncData 将服务器获取的数据传输到客户端(以及任何其他利用 the Nuxt payload 的内容)时,payload 使用 devalue 进行序列化。这允许我们不仅传输基本的 JSON,还可以序列化和恢复/反序列化更高级的数据类型,例如正则表达式、Dates、Map 和 Set、refreactiveshallowRefshallowReactiveNuxtError 等。

也可以为您自己的 Nuxt 不支持的类型定义序列化器/反序列化器。您可以在 useNuxtApp 文档中阅读更多内容。

请注意,这 不适用 使用 $fetchuseFetch 获取时从服务器路由传递的数据 - 有关更多信息,请参阅下一节。

序列化来自 API 路由的数据

当从 server 目录获取数据时,响应使用 JSON.stringify 进行序列化。但是,由于序列化仅限于 JavaScript 原始类型,Nuxt 会尽力转换 $fetchuseFetch 的返回类型以匹配实际值。

了解更多关于 JSON.stringify 的限制。

示例

server/api/foo.ts
export default defineEventHandler(() => {
  return new Date()
})
app.vue
<script setup lang="ts">
// Type of `data` is inferred as string even though we returned a Date object
const { data } = await useFetch('/api/foo')
</script>

自定义序列化函数

要自定义序列化行为,您可以在返回的对象上定义 toJSON 函数。如果您定义了 toJSON 方法,Nuxt 将尊重该函数的返回类型,并且不会尝试转换类型。

server/api/bar.ts
export default defineEventHandler(() => {
  const data = {
    createdAt: new Date(),

    toJSON() {
      return {
        createdAt: {
          year: this.createdAt.getFullYear(),
          month: this.createdAt.getMonth(),
          day: this.createdAt.getDate(),
        },
      }
    },
  }
  return data
})
app.vue
<script setup lang="ts">
// Type of `data` is inferred as
// {
//   createdAt: {
//     year: number
//     month: number
//     day: number
//   }
// }
const { data } = await useFetch('/api/bar')
</script>

使用替代序列化器

Nuxt 目前不支持 JSON.stringify 以外的替代序列化器。但是,您可以将 payload 作为普通字符串返回,并利用 toJSON 方法来保持类型安全。

在下面的示例中,我们使用 superjson 作为我们的序列化器。

server/api/superjson.ts
import superjson from 'superjson'

export default defineEventHandler(() => {
  const data = {
    createdAt: new Date(),

    // Workaround the type conversion
    toJSON() {
      return this
    }
  }

  // Serialize the output to string, using superjson
  return superjson.stringify(data) as unknown as typeof data
})
app.vue
<script setup lang="ts">
import superjson from 'superjson'

// `date` is inferred as { createdAt: Date } and you can safely use the Date object methods
const { data } = await useFetch('/api/superjson', {
  transform: (value) => {
    return superjson.parse(value as unknown as string)
  },
})
</script>

技巧

通过 POST 请求使用 SSE(服务器发送事件)

如果您通过 GET 请求使用 SSE,可以使用 EventSource 或 VueUse composable useEventSource

通过 POST 请求使用 SSE 时,您需要手动处理连接。以下是如何操作:

// Make a POST request to the SSE endpoint
const response = await $fetch<ReadableStream>('/chats/ask-ai', {
  method: 'POST',
  body: {
    query: "Hello AI, how are you?",
  },
  responseType: 'stream',
})

// Create a new ReadableStream from the response with TextDecoderStream to get the data as text
const reader = response.pipeThrough(new TextDecoderStream()).getReader()

// Read the chunk of data as we get it
while (true) {
  const { value, done } = await reader.read()

  if (done)
    break

  console.log('Received:', value)
}

发起并行请求

当请求彼此不依赖时,您可以使用 Promise.all() 并行发起请求以提高性能。

const { data } = await useAsyncData(() => {
  return Promise.all([
    $fetch("/api/comments/"), 
    $fetch("/api/author/12")
  ]);
});

const comments = computed(() => data.value?.[0]);
const author = computed(() => data.value?.[1]);