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> }