API: The fetch Method
The fetch
method, if set, is called every time before loading the component (only for page components). It will be called server-side once (on the first request to the Nuxt app) and client-side when navigating to further routes.
The fetch
method receives the context
object as the first argument, we can use it to fetch some data and fill the store. To make the fetch
method asynchronous, return a Promise, Nuxt.js will wait for the promise to be resolved before rendering the component.
Example of pages/index.vue
:
You can also use async
/await
to make your code cleaner:
store/index.js
Listening to query string changes
The fetch
method is not called on query string changes by default. If you want to change this behavior, for example when building a pagination component, you can setup parameters that should be listened to through the watchQuery
property of your page component. Learn more on the API page.