Nuxt.JS Asynchronous Data

From WikiOD

Nuxt.js extends Vue.js and adds a method called asyncData, which allows us to asynchronously obtain or process data before setting the data of the component.

asyncData method[edit | edit source]

The asyndeta method will be called before each load of the component (limited to the page component). It can be called before the server or route update. When this method is called, the first parameter is set to the context object of the current page . You can use the asyncData method to get the data. Nuxt.js will return the data returned by the data fusion component data method returned by asyndeta. To the current component.

Note: Since the asyndeta method is called before the component is initialized, there is no way to refer to the instance object of the component through this in the method.Nuxt.js provides several different ways to use the asyndeta method, you can choose the one you are familiar with:

  1. Return a Promise, and nuxt.js will wait for the Promise to be resolved before setting the component's data and rendering the component.
  2. Use  async or await  ( learn more )

We use  axios to  reconstruct HTTP requests, and we strongly recommend that you use our  axios module  for your Nuxt project.

If you directly use axios in node_modules in your project, and use axios.interceptors to add interceptors to process the request or response data, make sure to use axios.create to create an instance before using it. Otherwise, if the page is refreshed multiple times to request the server, the server rendering will repeatedly add interceptors, resulting in data processing errors.

If you directly use axios in node_modules in your project, and use axios.interceptors to add interceptors to process the request or response data, make sure to use axios.create to create an instance before using it. Otherwise, if the page is refreshed multiple times to request the server, the server rendering will repeatedly add interceptors, resulting in data processing errors.

import axios from 'axios'
 const myaxios = axios.create({
   // ...
 })
 myaxios.interceptors.response.use(function (response) {
   return response.data
 }, function (error) {
   // ...
 })
Return Promise[edit | edit source]
{
   asyncData ({ params }) {
     return axios.get(`<nowiki>https://my-api/posts/${params.id}`</nowiki>)
       .then((res) => {
         return { title: res.data.title }
       })
   }
 }
Use async or await[edit | edit source]
export default {
   async asyncData ({ params }) {
     const { data } = await axios.get(`<nowiki>https://my-api/posts/${params.id}`</nowiki>)
     return { title: data.title }
   }
 }

= Use callback function[edit | edit source]

export default {
   asyncData ({ params }, callback) {
     axios.get(`<nowiki>https://my-api/posts/${params.id}`</nowiki>)
       .then((res) => {
         callback(null, { title: res.data.title })
       })
   }
 }


Return object[edit | edit source]

If the data of the component does not need to be acquired or processed asynchronously, the specified literal object can be directly returned as the data of the component.

export default {
   data () {
     return { foo: 'bar' }
   }
 }
Data presentation[edit | edit source]

After the data returned by the asyncData method is merged with the data returned by the data method, it is returned to the template for display, such as:

<template>
 <nowiki> </nowiki> <nowiki><h1>{{ title }}</nowiki><nowiki></h1></nowiki>
 </template>
Context object[edit | edit source]

The  API context  can be used to understand all the properties and methods of the object.

Use the req/res(request/response) object[edit | edit source]

When calling asyncData on the server side, you can access the req and res objects requested by the user.

export default {
   async asyncData ({ req, res }) {
     // Please check if you are on the server side
     //Use req And res
     if (process.server) {
       return { host: req.headers.host }
     }
 
     return {}
   }
 }
Access dynamic routing data[edit | edit source]

You can use the context object injected into the asyncData attribute to access dynamic routing data. For example, the dynamic path parameter can be accessed using the name of the file or folder in which it is configured. So, if you define a file named _slug.vue, you can access it through context.params.slug.

export default {
   async asyncData ({ params }) {
     const slug = params.slug // When calling /abc the slug will be "abc"
     return { slug }
   }
 }
Monitor query parameter changes[edit | edit source]

By default, the query change will not call the asyncData method. If you want to monitor this behavior, for example, when building a paging component, you can set the parameter to be monitored through the watchQuery property of the page component. Learn more about API watchQuery .

Error handling[edit | edit source]

Nuxt.js provides an error(params) method in the context object. You can call this method to display the error information page. params.statusCode can be used to specify the request status code returned by the server.

\Take an example of returning Promise:

export default {
   asyncData ({ params, error }) {
     return axios.get(`<nowiki>https://my-api/posts/${params.id}`</nowiki>)
       .then((res) => {
         return { title: res.data.title }
       })
       .catch((e) => {
         error({ statusCode: 404, message: 'Post not found' })
       })
   }
 }

If you use the callback function, you can pass the error information object directly to the callback function, and Nuxt.js will automatically call the error method internally:

export default {
   asyncData ({ params }, callback) {
     axios.get(`<nowiki>https://my-api/posts/${params.id}`</nowiki>)
       .then((res) => {
         callback(null, { title: res.data.title })
       })
       .catch((e) => {
         callback({ statusCode: 404, message: 'Post not found' })
       })
   }
 }

If you want to customize the default error prompt page of Nuxt.js, please refer to the  page layout .