Vue 'serverPrefetch' Lifecycle Hook
Example
Using the serverPrefetch
lifecycle hook to fetch data on the server side.
export default {
data() {
return {
data: null,
};
},
async serverPrefetch() {
const response = await fetch("https://random-data-api.com/api/v2/users");
this.data = await response.json();
}
};
Definition and Usage
The serverPrefetch
lifecycle hook only happens during server-side rendering (SSR).
The serverPrefetch
lifecycle hook is used to for example fetch data, in case you need to do that exclusively on the server-side.
The serverPrefetch
lifecycle hook is used as an asynchronous function, so that if it returns a promise, the server will wait with rendering the component until the promise is resolved.
Note: In the example above, the "Run Example" button is missing because the example would not work as the serverPrefetch
hook will only be called during server-side rendering (SSR).
Related Pages
Vue Tutorial: Vue Lifecycle Hooks
JavaScript Tutorial: Asynchronous JavaScript