The opening

Before we begin, we need to clarify one question: what is server-side rendering?

In the past, rendering was more done on the client side, so why do we let the server do it now?

Are there any differences between server-side rendering and client-side rendering?

In fact, there are a lot of server-side rendering tools, looking at the manual will soon be able to get started, there is no difficulty, the key lies in what scenarios we need to use server-side rendering, what kind of rendering scheme is more suitable for our project; Learning, know how, we need to understand the service side rendering of the basic concept and principle of the service side rendering why, what is solved our problems, grasp the overall rendering logic and thinking, can we use in learning tools, at ease, and even tools have changed and updated later, we can with ease, No more “can’t learn”;

This logic is called the concept of tao, Dharma, shu and apparatus; Do not just stay in the use of tools and some of the tools of strange and crafty, more to the Dharma, dao level growth;

What is SSR?

Most of the modern front-end projects are single-page applications, which is what we call SPA. The whole application has only one page, and different page contents are displayed by means of components. After all the data is obtained by the request server, the client is assembled and displayed. This is the default rendering logic of the current front-end framework, which we call Client Side Render (CSR for short);

Load the rendering process as follows: HTML/CSS code –> load JavaScript code –> Execute JavaScript code –> render page dataThe biggest problem with client-side rendering for SPA applications is twofold:

1: The white screen lasts for a long time, resulting in poor user experience.

2: No content in HTML, SEO is not friendly;

The reason for this problem is that, when loading for the first time, the whole SPA script program needs to be downloaded, and the browser can only obtain the data to be displayed on the page after executing the code logic. However, the download of SPA script requires a long wait and execution time. Meanwhile, the SPA script downloaded to the browser has no page data. The browser actually does not have much rendering work, so users see a page without any content, not only that, because there is no content in the page, the search engine crawler crawls to the blank content, which is not conducive to SEO keyword acquisition;

Compared with the traditional site, browser pages are processed by the server has content static pages, back-end programming experience may be more familiar with some, page structure and content, are processed by the server, returned to the client;

The whole universe starting diagram, the whole process display

Comparison of the two we will find that traditional site page data synthesis server in the background, and the application of SPA page data synthesis in the browser, but regardless of that, the final rendering, or to the browser to complete, so, don’t get me wrong, we here rendering of a service and the client rendering, refers to the page structure and data synthesis, It’s not a browser presentation job;

So can we use the ideas of traditional websites to solve the problems of SPA and retain the advantages of SPA? Whether long hang time or SEO is not friendly, practical is the first screen page structure back to the browser first, and then to get the data after synthesis problems, so, the first screen page structure and data, as long as like traditional site, first on the server returned again after synthesis, at the same time put the SPA script loading is still in the first screen, At this point, the returned page is the complete content of the structure and data, so that the browser can load the SPA script when displaying the home page data, and the crawler of the search engine can also obtain the corresponding data, to solve the problem of SEO; To better understand this logic, I drew a flow chart:

Yes, this is the basic logic of what we call Server Side Rendering, which is SSR (Server Side Rendering);

The problem of long white screen time is solved because the server returns the rendered static page and reloads the request SPA script in the static page when it is first loaded.

Basic principle: the content and data of the home page are generated into a static page before the user requests, and the script code of SPA is introduced. After the static page is rendered by the browser, SPA script application is requested, and the subsequent page interaction is still client rendering.

Understand the principle of it, that is, to the realm of tao and law, next, let us descend to the application level of the art and apparatus to feel;

The React framework corresponds to the Next. Js framework, and the Vue framework corresponds to the Nuxt.js framework. Of course, if you are not interested in these, you can also implement an SSR server application. I wrote one myself before, if you are interested, want to see my implementation of the code, you can leave a message to me, back to make a tutorial sent;

We take nuxt.js corresponding to Vue as an example to concretely feel the server-side rendering;

Nuxt. Js applications

Nuxt.js is a general application framework based on vue.js. Nuxt.js presets the configuration required to develop a server-side rendered application using vue.js, providing the ability to generate a corresponding static site for vue.js-based applications. There are two ways to install the scaffolding: one is to use the create-NuxT-app scaffolding tool, and the other is to manually create the scaffolding yourself.

The installation

Scaffolding installation

NPX create-nuxt-app creact-nuxt: NPX create-nuxt

Then, there will be a lot of options in the command line, including project name, development language, UI component library, server framework, test framework, HTTP request library and so on. You can choose according to your own needs. After the installation is successful, the command line will give the corresponding prompt information.

We can run the project according to the prompt information. There are two running modes of the project: development environment and production environment. In the development environment, we can use NPM run dev directly, but to run the production environment, we need to build and compile first.

Since the project was just initialized, we didn’t write anything, so whatever we do, we see the following page;

Manual installation

Different from scaffolding installation, manual installation requires us to create the project and install the required extensions and plug-ins, we also need to write our own component code, and then configure the execution command, to start running, but manual creation is more test of the overall control ability of the project;

Run the mkdir nuxtnpm command to create a folder and switch to the CD nuxtnpm directory.

Then execute the command: NPM init -y to create the project and generate package.json file;

Use NPM install nuxt –save to install the nuxt.js framework.

Create pages directory and pages/index.vue component file in nuxtnpm directory.

<template>
  <div>
    <h2> 嗨 Nuxt.js </h2>
  </div>
</template>

<script>
export default {

}
</script>
Copy the code

Finally, we also configure the script parameters to run the command in the package.json file:

  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"."dev": "nuxt"."build": "nuxt build"."start": "nuxt start"."generate": "nuxt generate"
  },
Copy the code

After the command parameters are configured, it is the same as before:

NPM run dev starts a hot loaded Web server (development mode)

NPM run Build builds projects, uses Webpack to build applications, compresses JS and CSS resources (for distribution);

NPM run start Starts a Web server in production mode (requires project compilation first).

After the project runs, we can see the content of the component we just wrote;

It is important to note that the Pages directory is required, and the nuxt.js framework automatically reads all.vue files in this directory and automatically generates the corresponding routing configuration.

routing

Based on the routing

Basic routes do not need to be configured. Nuxt.js automatically generates routes based on folders and files in Pages

Suppose the directory structure of Pages is as follows:

pages/
--| user/
-----| index.vue
-----| one.vue
--| index.vue
Copy the code

So nuxt.js automatically generates the following route configuration:

router: {
  routes: [{name: 'index'.path: '/'.component: 'pages/index.vue'
    },
    {
      name: 'user'.path: '/user'.component: 'pages/user/index.vue'
    },
    {
      name: 'user-one'.path: '/user/one'.component: 'pages/user/one.vue'}}]Copy the code

Similarly, in the /.nuxt/router.js file, we can also see relevant content;

Routing navigation

The nuXT-Link component is used to add links to the page and jump to other pages. The nuxT-Link component is used to add links to other pages.

currently functions as router-link. It is recommended to read the Vue routing documentation to understand how it is used, so you can use it in NUxT as well as in Vue.

The use of programmatic navigation is the same as in Vue:

<template> <div> <h2>nuxt-link: </h2> <nuxt-link to="/user/info">Go to user</nuxt-link> <h2> Programmed navigation jump: </h2> <button @click="clickBtn">Go to user</button> </div> </template> <script> import axios from 'axios' export default  { methods:{ clickBtn(){ this.$router.push('/user') } } } </script>Copy the code

Dynamic routing

To define a dynamic route with parameters in nuxt.js, create a Vue file or directory prefixed with an underscore.

The name after the underscore is optional, but the file name is the keyword to obtain dynamic route parameters. The usage of vue-router is basically the same as that of vue-router:

\pages\user_kk.vue

<template> <div class="mis"> <h3> Dynamic route-route </h3> <! --> <p> Get parameters, print: {{$route.params.kk}}</p> </div> </template> <script> export default {mounted(){$route.params.kk}} Console. log(this.$route.params.kk)}} </script> <style>. Mis {background: coral; } </style>Copy the code

Visit: http://localhost:3000/user/3

Dynamic routing is ignored when nuxt.js executes generate.

Embedded routines by

You can create nested routes for nuxt.js applications using vue-Router children. To create an inline child path, you need to add a Vue file and a directory with the same name as the file to store the child view components. Add
to the parent component (.vue file) to display the child view content.

Parent component file contents

\pages\order.vue

<template> <div> <h2> Nuxt-child /> </div> </template> <script> export default {}Copy the code
Nested child component files and content

/ pages/order/index. Vue nested components, according to the default access path: http://localhost:3000/order

<template> <div> <p> Nested subroute -index </p> </div> </template> <script> export default {} </script>Copy the code

/ pages/order/info. The vue access path: http://localhost:3000/order/info

<template>
  <div>
    order->info
  </div>
</template>
Copy the code

/ pages/order/list. Vue access path: http://localhost:3000/order/list

<template> <div> <p> order-> list</p> <p>{{dataObj[0].name}}</p> </div> </template> <script> import axios from 'axios' Export default {async asyncData({params}) {// Send async asyncData({params}) {const {data} = await axios.get(' http://127.0.0.1 '); // Const dataObj = JSON. Parse (data); Return {dataObj}; // Nuxt merges data from the data method to the component without additional code. }, } </script>Copy the code

Asynchronous data -asyncData

Nuxt.js extends vue.js to add a method called asyncData that allows us to asynchronously fetch or process data before setting the component’s data. 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. Nuxt.js returns the data returned by asyncData’s data fusion component method to the current component.

<template> <div> user-index page <hr /> <! <div v-for="v in dataObj"> <h3>{{v.name}}</h3> </div> </template> <script> import axios from "axios"; Export default {async asyncData({params}) {// Send async asyncData({params}) {const {data} = await axios.get(' http://127.0.0.1 '); // Const dataObj = JSON. Parse (data); Return {dataObj}; // Nuxt merges data from the data method to the component without additional code. }}; </script>Copy the code

Nuxt.js support for SSG

SSG (Static Site Generators) before we begin, we need to know what SSG means.

It’s a scheme that generates static files for all the pages used in the application; Static site generation scheme, more suitable for CDN, cache, content data unchanged pages, such as: publicity pages, blog articles, help documents, news pages, e-commerce product list and many other application scenarios; Because the pages are pre-generated, once built, repeatedly used, fast access.

So how do you statically export an application in nuxt.js? The NPM run generate command is specifically designed for static export. Nuxt generates HTML static site resources for all the application content based on the route configuration. This command creates a dist folder with all the static resource files.

Dynamic routing is ignored when nuxt.js executes generate.

Dynamic routes are manually configured

If you want nuxt.js to generate static files for dynamic routes, you need to specify the value of the dynamic route parameter and configure it in the Routes array.

We can configure the /users/:id route in nuxt.config.js as follows:

module.exports = {
  generate: {
    routes: ['/users/1'.'/users/2'.'/users/3']}}Copy the code

Dynamic routing data generation

But what if the route dynamic parameter values are dynamic rather than fixed?

You can use a function that returns a Promise object type, meaning that you send a request to get all the data, generate all the possible routes from the returned data, and then generate all the static files from all the routes

nuxt.config.js

const axios = require('axios')

module.exports = {
  generate: {
    // Generate routing files instead of directories
    subFolders:false.routes() {
      // Request data
      return axios.get('http://127.0.0.1:80/three').then(res= > {
        const resData = JSON.parse(res.data);
        return resData.map(user= > {
          // Assemble the route
          return '/user/' + user.id
        })
      })
    }
  }
}
Copy the code

Asynchronous data n/A asyncData and Mounted are distinguished

Mounted When a static site is generated, the code is compiled into a statically generated JS file, and will be executed only when the browser renders it.

When exporting a static site, asyncData executes the code and compiles the data directly into HTML. The code is not compiled into the JS of a static file.

Focus on praise, don’t skimp;