Middle
Have you worked with asyncData in Nuxt? What is it used for?
sobes.tech AI
Answer from AI
In Nuxt.js, asyncData is used to load data asynchronously before rendering the page. This allows fetching necessary data on the server (SSR) or before the page is displayed on the client.
Main features of asyncData:
- Called before creating the page component.
- Allows fetching data and passing it to the component as props.
- Works only in page components, not in regular components.
Example usage:
export default {
async asyncData({ params, $axios }) {
const post = await $axios.$get(`/api/posts/${params.id}`)
return { post }
}
}
In this example, post data is loaded before the page is rendered and becomes available in the component via this.post. This improves SEO and user experience, as the page displays with the necessary data immediately.