useNuxtData
存取資料獲取組合式函式的當前快取值。
用法
下面的範例顯示如何在從伺服器獲取最新資料時,使用快取資料作為預留位置。
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 useAsyncData 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> }