元件選項
asyncData
和 fetch
Nuxt 3 提供了用於從 API 獲取資料的新選項。
同構 Fetch
在 Nuxt 2 中,你可能會使用 @nuxtjs/axios
或 @nuxt/http
來獲取資料 - 或者只是填充全域性的 fetch
。
在 Nuxt 3 中,你可以使用一個全域性可用的 fetch
方法,它與Fetch API或 $fetch
方法具有相同的 API,它使用unjs/ofetch。它有許多優點,包括
- 如果它在伺服器上執行,它會“智慧地”處理直接 API 呼叫,或者如果它在客戶端執行,則會向你的 API 發出客戶端呼叫。(它還可以處理呼叫第三方 API。)
- 此外,它還具有便利功能,包括自動解析響應和字串化資料。
可組合項
Nuxt 3 提供了用於資料獲取的新可組合項:useAsyncData
和 useFetch
。它們各自都有“惰性”變體(useLazyAsyncData
和 useLazyFetch
),它們不會阻塞客戶端導航。
在 Nuxt 2 中,你會使用類似於以下語法的元件來獲取資料:
export default {
async asyncData ({ params, $http }) {
const post = await $http.$get(`https://api.nuxtjs.dev/posts/${params.id}`)
return { post }
},
// or alternatively
fetch () {
this.post = await $http.$get(`https://api.nuxtjs.dev/posts/${params.id}`)
},
}
在你的方法和模板中,你可以使用 post
變數,就像使用元件提供的任何其他資料一樣。
使用 Nuxt 3,你可以在 setup()
方法或 <script setup>
標籤中使用可組合項來執行資料獲取
<script setup lang="ts">
// Define params wherever, through `defineProps()`, `useRoute()`, etc.
const { data: post, refresh } = await useAsyncData('post', () => $fetch(`https://api.nuxtjs.dev/posts/${params.id}`))
// Or instead - useFetch is a convenience wrapper around useAsyncData when you're just performing a simple fetch
const { data: post, refresh } = await useFetch(`https://api.nuxtjs.dev/posts/${params.id}`)
</script>
你現在可以在 Nuxt 3 模板中使用 post
,或者呼叫 refresh
來更新資料。
useFetch
並不是 fetch()
鉤子的直接替代品。相反,useAsyncData
替代了這兩個鉤子,並且更具可定製性;它不僅僅是簡單地從端點獲取資料。useFetch
是 useAsyncData
的一個方便的包裝器,用於簡單地從端點獲取資料。遷移
- 將頁面/元件中的
asyncData
鉤子替換為useAsyncData
或useFetch
。 - 將元件中的
fetch
鉤子替換為useAsyncData
或useFetch
。
head
key
你現在可以在 definePageMeta
編譯器宏中定義一個鍵。
- <script>
- export default {
- key: 'index'
- // or a method
- // key: route => route.fullPath
- }
+ <script setup>
+ definePageMeta({
+ key: 'index'
+ // or a method
+ // key: route => route.fullPath
+ })
</script>
layout
loading
此功能在 Nuxt 3 中尚不支援。
middleware
scrollToTop
此功能在 Nuxt 3 中尚不支援。如果你想覆蓋 vue-router
的預設滾動行為,你可以在 ~/router.options.ts
中進行(詳見文件)。類似於 key
,在 definePageMeta
編譯器宏中指定它。
- <script>
- export default {
- scrollToTop: false
- }
+ <script setup>
+ definePageMeta({
+ scrollToTop: false
+ })
</script>
transition
validate
Nuxt 3 中的 validate 鉤子只接受一個引數:route
。就像 Nuxt 2 中一樣,你可以返回一個布林值。如果你返回 false 並且找不到其他匹配項,這將意味著 404。你也可以直接返回一個帶有 statusCode
/statusMessage
的物件,以立即響應錯誤(不會檢查其他匹配項)。
- <script>
- export default {
- async validate({ params }) {
- return /^\d+$/.test(params.id)
- }
- }
+ <script setup>
+ definePageMeta({
+ validate: async (route) => {
+ const nuxtApp = useNuxtApp()
+ return /^\d+$/.test(route.params.id)
+ }
+ })
</script>
watchQuery
Nuxt 3 不支援此功能。你可以直接使用 watcher 來觸發資料重新獲取。
<script setup lang="ts">
const route = useRoute()
const { data, refresh } = await useFetch('/api/user')
watch(() => route.query, () => refresh())
</script>