Hello, I am Cangcang Liangliang, a front-end developer. At present, I am publishing some interesting and knowledge about front-end learning on Nuggets, Zhihu and my personal blog. Welcome to follow me.


Recently, when I was looking for problems with the Nuxt project for a colleague, I found that Nuxt provides two life cycles:

  • asyncData
  • fetch

The introduction of these two life cycles in the Chinese document is very short, and I am at a loss after reading it. After repeated research and various tests, I have roughly understood the purpose and usage of these two life cycles.

1. asyncData

The asyncData method is called before each load of the component (page component only). It can be invoked before a server or route is updated. 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 fetch data. Nuxt.js returns the data returned by the asyncData component data method to the current component.

Simply put, asyncData can only be used for page components, not custom components. It can return an object whose value overrides the corresponding property value in data.

And asyncData does not have this to refer to the component instance, but it does have a context parameter, which is used roughly as follows:

<template>
  <div>{{ content }}</div>
</template>

<script lang="ts">
import Vue from "vue";

export default Vue.extend({
  name: "IndexPage".async asyncData({$axios}) {
    const res = await $axios.$get("http://localhost:5000");
    return {content: res.content};
  },
  data() {
    return {
      content: ""}; }});</script>
Copy the code

View the web source code:

2. fetch

The FETCH method is used to populate the application’s store data before rendering the page, similar to the asyncData method except that it does not set the component’s data.

Can be used in any component, be it a page component or a custom component.

It is important to note that the content above the Chinese document is out of date and highly misleading due to the issue of obsolescence:

This can now be used in fetch to fetch component instances, and it can also be used to change properties in data. In The English document, the official introduction of FETCH is very perfect, unlike the Chinese document where fetch is just a paragraph of text.

According to the English documentation, the use of fetch in Nuxt version 2.12 and later is completely different from the previous version, and if you accept a context object in a FETCH, it will be treated as an older version of FETCH, which is now officially not recommended.

I didn’t read the English document properly before, so I found a flaw in my experiment. Let’s just look at the following code:

async fetch() {
  const res = await fetch('http://localhost:5000').then(res= >res.json());
  // The interface renders correctly after the assignment
  this.content = res.content;
},
Copy the code

After I change the request:

async fetch({ $axios }) {
  const res = await $axios.$get('http://localhost:5000');
  // The interface does not render the corresponding value
  this.content = res.content;
},
Copy the code

I changed the request method to the axios that came with Nuxt, and I found that the content on the page was not rendering properly, and I had no idea why.

According to the English documentation, context cannot be used in fetch, and if you use context, it will be treated as an old fetch.

If you want to use context, asyncData or anonymous middleware is recommended, so the above request should read:

async fetch() {
  // Get $axios from this instead of context
  const res = await this.$axios.$get("http://localhost:5000");
  // The interface renders the data correctly
  this.content = res.content;
},
Copy the code

View the web source code:

3. Traditional requests

Now that we know the general usage of asyncData and FETCH, we need to see why these two lifecyres are used for requests and why not network requests in the common lifecyres of Created and Mounted Vue.

Or the request above:

async mounted() {
  const res = await this.$axios.$get("http://localhost:5000");
  this.content = res.content;
},
Copy the code

View the web source code:

Mounted Mounted Mounted mounted mounted mounted mounted mounted mounted mounted mounted mounted

If you want to reduce the stress on the server side, such as some request data that is not helpful for SEO, then you can put it in Mounted because the Mounted life cycle runs on the client side.

As for the Created lifecycle, it runs once on the server and again on the client when I test it.

This may be related to the Nuxt life cycle, I haven’t gone into it yet, so I don’t have a say, and the official state is that if you want to use traditional Vue requests, put them in the Mounted life cycle.

4. User information

Using these two life cycles can make your project achieve better SEO, but it is worth noting that both life cycles are run in the server, and the server does not have window objects, so it cannot use localStorage. If you want to authenticate the user, So the recommendation is to use cookies to store the user’s identity information.

Js-cookie can be very convenient to operate cookies.

5. Good

Now many search engine crawlers can parse JavaScript files to get the important content of JavaScript files.

However, there is no way to obtain the data of asynchronous request. Therefore, asyncData and FETCH are used to put some important data on the server for request, and then the server sends back the HTML to the client to obtain the data, which has two advantages:

  • Short white screen time.
  • Better SEO.

When a lot of data is requested asynchronously, page collapse often occurs when opening the page, and the page will be displayed normally after the data rendering is completed. Although it may be only for a moment, it will also cause bad experience for users.

With server rendering, you don’t have these problems, because the data is already fetched on the server, so you don’t have to temporarily crash the page.

6. The final

Server rendering better SEO at the same time, it is also the index of the burden of server times, such as single application page layout to Nginx might account for several megabytes of memory, and if the server is rendering the case could reach several hundred M or more, you know, the server’s memory is very expensive, however, memory is doubling every, prices will be multiplied several times.

As for whether to do server rendering or not, it depends on your own situation, but when it comes to outsourcing projects like official website, if you use Vue technology stack then Nuxt is definitely the right choice.

Clients don’t do SEO, you can package it as a single page application, and if you need SEO, you can start rendering on the server side without any pressure, doing more preparation and less overtime.