Nuxt.js Learning - Asynchronous Data

[TOC]

1. Asynchronous data

1.1. Official documents:

Nuxt.js extends Vue.js by adding a method called asyncData that allows us to get or process data asynchronously before setting up the data for a component.

asyncData method

The asyncData method is called before each load of the component (page component only).It can be invoked on the server side or before routing updates.When this method is called, the first parameter is set to the current page's Context Object , you can use the asyncData method to get data, and Nuxt.js will return the data returned by the asyncData data data fusion component data method to the current component.

Note: Since the asyncData method is called before the component is initialized, there is no way to reference the component's instance object through this method.

Nuxt.js offers several different ways to use the asyncData method, and you can choose one that you are familiar with:

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

We use [axios] to refactor HTTP requests, and we strongly recommend that you use [axios module] for your Nuxt project.

If Axios in node_modules is used directly in your project, and you use axios.interceptors to add interceptors to process request or response data, be sure to create an instance using axios.create before using it.Otherwise, if the page is refreshed multiple times to request the server, server-side rendering will add interceptors repeatedly, 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 to Promise

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

1.2. Actual operations (practice examples)

1.2.1, Install Axios

Since Vue.js officially recommends Axios for remote data acquisition, use Axios and npm to install Axios as officially recommended

npm install axios --save

Use async or await

export default {
  async asyncData ({ params }) {
    const { data } = await axios.get(`https://my-api/posts/${params.id}`)
    return { title: data.title }
  }
}

Use callback functions

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

error handling

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

An example is returning Promise:

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

If you use a callback function, you can pass the wrong information object directly to the callback function, and the error method is automatically called inside Nuxt.js:

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

Create remote data

{
  "name": "Vestibular Clouds",
  "age": 18,
  "temp": "I love java!"
}

When you type, you get an address, which is the data request address you just entered.

https://api.myjson.com/bins/1bqqsw

First confirm that you have Axios installed and did not enter the following command to install
npm install axios --save

ansycData.vue

<template>
  <div>
    <h1>Full name:{{info.name}}</h1>
    <h2>Age:{{info.age}}</h2>
    <h2>Introduction:{{info.temp}}</h2>
  </div>
</template>

<script>
import axios from 'axios'
export default {
   data() {
     return {
      name:"111"
     }
   },
  async asyncData(){
  let{data} =await axios.get('https://api.myjson.com/bins/1bqqsw')
   return {info:data}
   } 
};
</script>

<style>
</style>

Show results:

Keywords: Front-end axios Vue npm Java

Added by homchz on Mon, 06 Jan 2020 01:21:33 +0200