Nuxt Nation 大会即将到来。加入我们,时间为 11 月 12-13 日。

useNuxtData

访问数据获取可组合函数的当前缓存值。
useNuxtData 使您可以访问 useAsyncDatauseLazyAsyncDatauseFetchuseLazyFetch 的当前缓存值,并显式提供键。

用法

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

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

乐观更新

我们可以利用缓存在突变后更新 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('')
const previousTodos = ref([])

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

const { data } = await useFetch('/api/addTodo', {
  method: 'post',
  body: {
    todo: newTodo.value
  },
  onRequest () {
    previousTodos.value = todos.value // Store the previously cached value to restore if fetch fails.

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

类型

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