useNuxtData

访问数据获取可组合项的当前缓存值。
useNuxtData 允许你通过显式提供的键访问 useAsyncDatauseLazyAsyncDatauseFetchuseLazyFetch 的当前缓存值。

用法

¥Usage

useNuxtData 可组合项用于访问数据获取可组合项(例如 useAsyncDatauseLazyAsyncDatauseFetchuseLazyFetch)的当前缓存值。通过提供数据获取期间使用的键,你可以检索缓存的数据并根据需要使用。

¥The useNuxtData composable is used to access the current cached value of data-fetching composables such as useAsyncData, useLazyAsyncData, useFetch, and useLazyFetch. By providing the key used during the data fetch, you can retrieve the cached data and use it as needed.

这对于通过重用已获取的数据或实现诸如乐观更新或级联数据更新之类的功能来优化性能特别有用。

¥This is particularly useful for optimizing performance by reusing already-fetched data or implementing features like Optimistic Updates or cascading data updates.

要使用 useNuxtData,请确保已使用显式提供的键调用数据获取可组合项(useFetchuseAsyncData 等)。

¥To use useNuxtData, ensure that the data-fetching composable (useFetch, useAsyncData, etc.) has been called with an explicitly provided key.

参数

¥Params

  • key:用于标识缓存数据的唯一键。此键应与原始数据提取期间使用的键匹配。

返回值

¥Return Values

  • data:对与提供的键关联的缓存数据的响应式引用。如果不存在缓存数据,则值为 null。如果缓存数据发生变化,此 Ref 会自动更新,从而实现组件的无缝响应。

示例

¥Example

以下示例展示了如何在从服务器获取最新数据时使用缓存数据作为占位符。

¥The example below shows how you can use cached data as a placeholder while the most recent data is being fetched from the server.

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>

乐观更新

¥Optimistic Updates

以下示例展示了如何使用 useNuxtData 实现乐观更新。

¥The example below shows how implementing Optimistic Updates can be achieved using useNuxtData.

乐观更新是一种假设服务器操作成功后立即更新用户界面的技术。如果操作最终失败,UI 将回滚到之前的状态。

¥Optimistic Updates is a technique where the user interface is updated immediately, assuming a server operation will succeed. If the operation eventually fails, the UI is rolled back to its previous state.

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>

类型

¥Type

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