useNuxtData
访问数据获取组合式函数的当前缓存值。
使用
useNuxtData 组合式函数用于访问数据获取组合式函数(例如 useAsyncData、useLazyAsyncData、useFetch 和 useLazyFetch)的当前缓存值。通过提供在数据获取期间使用的键,您可以检索缓存的数据并根据需要使用它。
这对于通过复用已获取的数据来优化性能,或实现诸如乐观更新(Optimistic Updates)或级联数据更新等功能特别有用。
要使用 useNuxtData,请确保调用数据获取组合式函数(useFetch、useAsyncData 等)时显式提供了键。
类型
签名
export function useNuxtData<DataT = any> (key: string): { data: Ref<DataT | undefined> }
参数
key:标识缓存数据的唯一键。此键应与原始数据获取期间使用的键相匹配。
返回值
data:与提供的键关联的缓存数据的响应式引用。如果不存在缓存数据,其值将为undefined。如果缓存数据发生变化,此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', (_nuxtApp, { signal }) => $fetch('/api/todos', { signal }))
</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>