Nuxt Nation カンファレンス開催! 11月12日~13日

useNuxtData

データ取得コンポーザブルの現在のキャッシュされた値にアクセスします。
useNuxtData は、明示的に指定されたキーを使用して、useAsyncDatauseLazyAsyncDatauseFetch、およびuseLazyFetch の現在のキャッシュされた値にアクセスできます。

使用方法

以下の例では、最新のデータがサーバーからフェッチされている間に、キャッシュされたデータを使用する方法を示しています。

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