useNuxtData

原始檔
訪問資料獲取組合式函式的當前快取值。
useNuxtData 允許您訪問 useAsyncDatauseLazyAsyncDatauseFetchuseLazyFetch 的當前快取值,前提是它們使用了明確提供的鍵。

使用

useNuxtData 組合式函式用於訪問資料獲取組合式函式(如 useAsyncDatauseLazyAsyncDatauseFetchuseLazyFetch)的當前快取值。透過提供在資料獲取期間使用的鍵,您可以檢索快取的資料並根據需要使用。

這對於透過重用已獲取的資料來最佳化效能或實現樂觀更新或級聯資料更新等功能特別有用。

要使用 useNuxtData,請確保資料獲取組合式函式(useFetchuseAsyncData 等)已明確提供鍵。

引數

  • key:標識快取資料的唯一鍵。此鍵應與原始資料獲取期間使用的鍵匹配。

返回值

  • data:對與所提供鍵關聯的快取資料的響應式引用。如果不存在快取資料,則該值為 null。如果快取資料發生變化,此 Ref 會自動更新,從而在您的元件中實現無縫的響應性。

示例

下面的示例演示瞭如何在從伺服器獲取最新資料時將快取資料用作佔位符。

app/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>
app/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 將回滾到其先前的狀態。

app/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>
app/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 () {
  await $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>

型別

簽名
export function useNuxtData<DataT = any> (key: string): { data: Ref<DataT | undefined> }