Nuxt (>= 2.12) Fetch

June 12, 2020

The easiest way to fetch data using Nuxt is via asyncData, as a lot of things is handled for you (loading animation, data merging, state management, etc) and it just works.

If you need more control, you should use fetch.

  • Render UI based on $fetchState (loading, error and success)
  • Have access to this / page component.
  • Ability to disable fetchOnServer forcing fetch to be called on client side only
  • Ability to call this.$fetch()
  • Enable fetch cache

Code

<template>
  <div>
    <div v-if="$fetchState.pending">Loading ...</div>
    <div v-else-if="$fetchState.error">Error: {{ $fetchState.error.message }}</div>
    <div>
      {{ title }}
    </div>
  </div>
</template>

<script>
export default {
  async fetch() {
    // const HOST = 'http://localhost:8080' // required for server-side fetch
    // const url = new URL(`/data/test.json`, HOST)
    const url = 'https://jsonplaceholder.typicode.com/posts/1'
    // alternatvely, you could use $axios or $http
    const res = await fetch(url)
    const data = await res.json()

    this.title = data.title
  },
  data() {
    return {
      title: null
    }
  },
}
</script>

References:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.