useNuxtData 组合式函数用于访问数据获取组合式函数(如 useAsyncData、useLazyAsyncData、useFetch 和 useLazyFetch)的当前缓存值。通过提供数据获取期间使用的键,您可以检索缓存的数据并根据需要使用它。
这对于通过重用已获取的数据来优化性能或实现乐观更新或级联数据更新等功能特别有用。
要使用 useNuxtData,请确保数据获取组合式函数(useFetch、useAsyncData 等)已明确提供键进行调用。
key:标识缓存数据的唯一键。此键应与原始数据获取期间使用的键匹配。data:对与所提供键关联的缓存数据的响应式引用。如果不存在缓存数据,则该值为 null。此 Ref 会在缓存数据更改时自动更新,从而在组件中实现无缝响应式。以下示例演示了如何在从服务器获取最新数据时使用缓存数据作为占位符。
<script setup lang="ts">
// We can access same data later using 'posts' key
const { data } = await useFetch('/api/posts', { key: 'posts' })
</script>
<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 会回滚到其先前的状态。
<script setup lang="ts">
// We can access same data later using 'todos' key
const { data } = await useAsyncData('todos', (_nuxtApp, { signal }) => $fetch('/api/todos', { signal }))
</script>
<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> }