透過 100+ 個技巧的集合來學習 Nuxt!

useNuxtData

存取資料擷取 composables 的目前快取值。
useNuxtData 讓您可以存取 useAsyncDatauseLazyAsyncDatauseFetchuseLazyFetch 具有明確提供的 key 的目前快取值。

用法

useNuxtData composable 用於存取資料擷取 composables (例如 useAsyncDatauseLazyAsyncDatauseFetchuseLazyFetch) 的目前快取值。 透過提供資料擷取期間使用的 key,您可以檢索快取資料並根據需要使用它。

這對於透過重複使用已擷取的資料或實作像是「樂觀更新」或「串聯資料更新」等功能來最佳化效能特別有用。

若要使用 useNuxtData,請確保資料擷取 composable (useFetchuseAsyncData 等) 已使用明確提供的 key 呼叫。

參數

  • key:識別快取資料的唯一 key。此 key 應與原始資料擷取期間使用的 key 相符。

傳回值

  • data:對與提供的 key 相關聯的快取資料的反應性參考。如果不存在快取資料,則值將為 null。如果快取資料變更,此 Ref 會自動更新,讓您的元件中實現無縫的反應性。

範例

以下範例示範如何在從伺服器擷取最新資料時,使用快取資料作為預留位置。

pages/posts.vue
<script setup lang="ts">
// We can access same data later using 'posts' key
const { data } = await useFetch('/api/posts', { key: 'posts' })
</script>
pages/posts/[id].vue
<script setup lang="ts">
// Access to the cached value of useFetch in posts.vue (parent route)
const { data: posts } = useNuxtData('posts')

const route = useRoute()

const { data } = useLazyFetch(`/api/posts/${route.params.id}`, {
  key: `post-${route.params.id}`,
  default() {
    // Find the individual post from the cache and set it as the default value.
    return posts.value.find(post => post.id === route.params.id)
  }
})
</script>

樂觀更新

以下範例示範如何使用 useNuxtData 實現「樂觀更新」。

「樂觀更新」是一種技術,使用者介面會立即更新,假設伺服器操作將會成功。 如果操作最終失敗,UI 將會回滾到先前的狀態。

pages/todos.vue
<script setup lang="ts">
// We can access same data later using 'todos' key
const { data } = await useAsyncData('todos', () => $fetch('/api/todos'))
</script>
components/NewTodo.vue
<script setup lang="ts">
const newTodo = ref('')
let previousTodos = []

// Access to the cached value of useAsyncData in todos.vue
const { data: todos } = useNuxtData('todos')

async function addTodo () {
  return $fetch('/api/addTodo', {
    method: 'post',
    body: {
      todo: newTodo.value
    },
    onRequest () {
      // Store the previously cached value to restore if fetch fails.
      previousTodos = todos.value

      // Optimistically update the todos.
      todos.value = [...todos.value, newTodo.value]
    },
    onResponseError () {
      // Rollback the data if the request failed.
      todos.value = previousTodos
    },
    async onResponse () {
      // Invalidate todos in the background if the request succeeded.
      await refreshNuxtData('todos')
    }
  })
}
</script>

類型

useNuxtData<DataT = any> (key: string): { data: Ref<DataT | null> }