透過超過 100 個技巧來學習 Nuxt!

$fetch

Nuxt 使用 ofetch 來全域公開 $fetch 輔助函數,用於發出 HTTP 請求。

Nuxt 使用 ofetch 來全域公開 $fetch 輔助函數,以便在您的 Vue 應用程式或 API 路由中發出 HTTP 請求。

在伺服器端渲染期間,呼叫 $fetch 來獲取您的內部 API 路由,將直接呼叫相關的函數(模擬請求),節省額外的 API 呼叫
在元件中使用 $fetch 而不使用 useAsyncData 包裹它,會導致兩次獲取資料:第一次是在伺服器端,然後在客戶端水合作用期間再次獲取,因為 $fetch 不會將狀態從伺服器傳輸到客戶端。因此,由於客戶端必須再次獲取資料,因此會在兩側執行獲取。

我們建議使用 useFetchuseAsyncData + $fetch 來防止在獲取元件資料時重複獲取資料。

app.vue
<script setup lang="ts">
// During SSR data is fetched twice, once on the server and once on the client.
const dataTwice = await $fetch('/api/item')

// During SSR data is fetched only on the server side and transferred to the client.
const { data } = await useAsyncData('item', () => $fetch('/api/item'))

// You can also useFetch as shortcut of useAsyncData + $fetch
const { data } = await useFetch('/api/item')
</script>
請閱讀 文件 > 入門 > 資料獲取 以了解更多資訊。

您可以在任何僅在客戶端執行的函式中使用 $fetch

pages/contact.vue
<script setup lang="ts">
function contactForm() {
  $fetch('/api/contact', {
    method: 'POST',
    body: { hello: 'world '}
  })
}
</script>

<template>
  <button @click="contactForm">Contact</button>
</template>
$fetch 是在 Nuxt 中發出 HTTP 呼叫的首選方式,而不是為 Nuxt 2 製作的 @nuxt/http@nuxtjs/axios
如果您使用 $fetch 在開發環境中呼叫具有自我簽署憑證的 (外部) HTTPS URL,則需要在您的環境中設定 NODE_TLS_REJECT_UNAUTHORIZED=0