Fetching Data With fetch() and asyncData()
Similar to middleware, fetch()
and asyncData()
are functions that are created by Nuxt and get executed before a page gets rendered. Middleware will be executed before fetch()
and asyncData()
. With that said, let’s focus on asyncData()
first. With asyncData
, you can “sync” your data or define data that you want to be rendered on the server side; asyncData
can only be applied to components in the pages
directory.
pages/index.vue
<script>
export
default
{
data
()
{
// client side data
return
{
city
:
'Cincinnati'
,
state
:
'Ohio'
,
}
},
asyncData
(
context
)
{
// server side data
return
{
country
:
'United States'
,
continent
:
'North America'
}
}
}
</script>
All of the data inside of asyncData
will be rendered on the server and not the client. Meaning, if there are chunks of data that are important to be rendered on the server, you must...