0
votes

I've used Vue as a client-side library for years but I unfortunately never dove into server-side rendering, or understand it much, for that matter. I was watching a few tutorials on it where it gave an example of normal client-side fetching with the mount() hook.

<template>
    <div v-for="item in items">
         <div> {{ item.name }} </div>
     </div>
</template>
data() {
   return {
     items: []
   }
}

mount() {
   fetch('http://www.myendpoint.com')
   .then(response => {
     this.items = response;
   }
}

vs using Nuxt's asyncData option instead:

<template>
    <div v-for="item in items">
         <div> {{ item.name }} </div>
     </div>
</template>

asyncData() {
   fetch('http://www.myendpoint.com')
   .then(response => {
     this.items = response;
   }
}

does this just mean that async data would run long before mountwould ever run since it's run before the component is even loaded so the data will be ready? What happens if that fetch call takes a while to load then...doesn't the same side effect happen? Rather than a component without data ready usingmount()` if the fetch takes long, you'd just have nothing at all loaded until the fetch completes if using SSR?

1

1 Answers

1
votes

Nuxt is basically a Vue app but with some server logic done before serving the SPA.

Here are the 2 ways of using some data fetching hooks in Nuxt:

  • fetch() (it's actual hook's name, nothing related to the fetch API), I do recommend to use this one
  • asyncData (pretty much the same but less flexible although can block the page render until all the data is properly fetched)

More info can be found between both here: https://nuxtjs.org/docs/2.x/features/data-fetching


A whole question is available here too: Difference between Asyncdata vs Fetch

Lastly, you probably saw the lifecyle for Vue: https://vuejs.org/v2/guide/instance.html#Lifecycle-Diagram
Here is the one of Nuxt, which adds a bit more layers to Vue's SPA only ones: https://nuxtjs.org/docs/2.x/concepts/nuxt-lifecycle