Client Rendering (CSR) implications

In client rendering mode, the server sends static files to the client, and the client takes the files sent by the server and runs JS. According to the results of JS running, the DOM is generated and rendered to the user.

Front-end rendering originated from the rise of JavaScript, and the popularity of Ajax has made front-end rendering more mature. Front-end rendering has realized the separation of front and back ends in a real sense. The front end only focuses on the development of UI, and the back end only focuses on the development of logic. The back-end provides JSON data, and the front-end loops json to generate the DOM to insert into the page.

Most platforms use client-side rendering. If you look at the source code of the home page, you will find that the HTML structure in the code is only a few simple sentences. When the first page is requested, the body returned is empty, then execute JS to inject HTML structure into the body, combined with CSS display;

<body>
	<div id=app></div>
	<script type=text/javascript src=/static/js/manifest.9476fbe0d0f0fe7c5038.js></script>
	...
</body>
Copy the code



Advantages and disadvantages of client-side rendering (CSR)

Advantages: small amount of data transmission network, reduce the server pressure, front and back end separation, local refresh, no need to request a complete page each time, good interaction can achieve a variety of effects

Disadvantages: bad for SEO, crawler can’t see the full program source code, slow rendering of the first screen (need to download a bunch of JS and CSS before rendering)





Meaning of server-side rendering (SSR)

Server-side rendering: When a user first requests a page, the server renders the required component or page into an HTML string and returns it to the client. What the client gets is HTML content that can be rendered and presented to the user without having to run through the JS code to generate the DOM content. Use server-side rendering of the site, so to speak"What you see is what you get"The content rendered on the page can also be found in the HTML source file. Below, when we look at the source of the web page, we can see the full content.


Advantages and disadvantages of server-side rendering (SSR)

Advantages: fast first screen rendering, SEO benefit, can generate cache fragments, generate static files, energy saving (compared to the power consumption of client rendering)

Disadvantages: High pressure on the server


When is server-side rendering used?

Through the concept of server-side rendering and its two characteristics: fast first screen loading speed, SEO optimization.

We know that server-side rendering is really something that the browser does, and we put it on the server side to do it.

The choice between rendering on the server side or on the Browser side depends more on the business scenario.





Introduction to common server rendering frameworks

Server-side rendering framework applications include Nuxt.js, next.js, etc.

Nuxt.js is a lightweight application framework based on Vue. It can be used to create server-side rendering (SSR) applications, and can also act as a static site engine to generate static site applications, with elegant code structure layering and hot loading features.

Next. Js is a lightweight React server rendering application framework. Provides all the functionality and best development experience you need in a production environment: static and server-side converged rendering, TypeScript support, smart packaging, route prefetch, and more without any configuration.

If you’re used to vUE development, Nuxt is a good way to get started. Nuxt.js: Nuxt.js: nuxt.js: nuxt.js: nuxt.js: nuxt.js


Create an SSR project with the scaffolding tool create-nuxT-app

To get started quickly, the Nuxt.js team created the scaffolding tool create-NuxT-app.

npx create-nuxt-app nuxtdemo
Copy the code

It lets you choose a server-side framework to integrate, a UI framework you like, a testing framework, adding AXIos, Eslint, Prettier, etc. Just choose according to the project requirements. For example, select None for the server framework (Nuxt’s default server) and Element UI for the UI framework.

Once checked, it will install all dependencies, so the next step is to start the project directly:

cd nuxtdemo
npm run dev
Copy the code

At this point, we should see a simple project setup by default, as shown below:


├─ Uncompiled Static Resources such as LESS, SASS or JavaScript ├─ Components ├─ Layouts layout Component for organizing applications ├─ Middleware ├─ Nuxt.config.js for organizing nuxt.js Personalization of applications, To override the default Settings ├─ Package. json used to describe application dependencies and exposed script interface ├─ pages used to organize application routing and view ├─ plugins to store JAVASCRIPT plug-ins that need to be run before the root vue.js application is instantiated Static Static file for storing applications (not processed by WebPack compilation) ├─ Store Vuex state tree for applicationCopy the code

Now that we know what each file does, let’s build a simple website using nuxt.js. Use a simple website to explain the basics of nuxt.js.


Nuxt. Introduction to js

We use Nuxt.js to build a common web framework, including common headers, bottoms, dynamic routing, nested routing, error pages, and how to reference common styles, common methods, and route validation in nuxt.js. Let’s start with the finished image of the website

Download link:

https://github.com/helloann/nuxtdemo

This is a simple site with a public head and tail. The home page is a list of articles, using a dynamic route, click into the corresponding article can jump. The staff introduction page uses nested routines. Click on the left side of the personnel, the right side can be corresponding to the information of the personnel. Ok, let’s get started.

layout

Most websites have a common header and bottom. In previous projects, we had to manually import the header and tail components. As follows:

import header from '@/publicResource/components/header.vue' import footer from '@/publicResource/components/footer.vue' . export default { components: { 'v-header': header, 'v-footer': footer } }Copy the code

But in Nuxt.js you don’t have to. We create our custom layout directly in the Layout directory. Modify the layouts/default.vue file to extend the default layout of your application

<template>
  <div>
    <v-header></v-header>
    <nuxt />
    <v-footer></v-footer>
  </div>
</template>

<script>
import Header from '~/components/Header.vue'
import Footer from '~/components/Footer.vue'
export default {
  components: {
    'v-header': Header,
    'v-footer': Footer
  },
  data () {
    return { }
  }

}
</script>
Copy the code

The
component is used to display the body of the page. In this way, all pages will automatically have a header and a tail, without special declaration and introduction. If some page layouts don’t need headers or tails, it’s easy to just tell the page which custom layout to use.

<template> <! -- Your template --> </template> <script> export default { layout: 'blog' // page component definitions } </script>Copy the code

Error page

You can also customize the error page by editing the layouts/error.vue file. This layout file does not need to contain the
tag. Think of this layout file as a component that displays application errors (404,500, etc.).

<template> <div class="error-wrap"> <p v-if=" error-. statusCode === 404" class="info"> Page does not exist </p> <p class="info" </p> <p><nuxt-link to="/"> </p> </div> </template> <script> export default {props: ['error'], } </script>Copy the code

Based on the routing

Nuxt.js does not need to compile a route configuration file. You only need to name and store the file according to API requirements to automatically generate a route configuration file. For example, we need to add a new people introduction page Users. Just add the Users page under Pages and the route will be automatically generated. Suppose the directory structure of Pages is as follows:

pages/
--| users.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: 'users',
      path: '/users',
      component: 'pages/users.vue'
    }
  ]
}
Copy the code

Nuxt-link can be used directly when referencing other pages

<nuxt-link to="/users">Copy the code

Similarly, we can name and store files according to the framework. You can generate configuration files for dynamic routes and nested routes without configuring routes.

Dynamic routing

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

├ ─ ─ pages ├ ─ ─ ─ ─ ─ ─ blogs │ └ ─ ─ ─ _blog. Details of the vue blog page ├ ─ ─ ─ ─ ─ ─ index. The vue home pageCopy the code

Suppose we write a list of articles in index.vue and link to the corresponding article page as follows:

<template> <div class="container"> <div class="bm-sider"> {{content}} </div> <div class="bm-con"> <ul> <li><nuxt-link To = "blogs / 1" > this is the article 1 < / nuxt - link > < / li > < li > < nuxt - link to = "blogs / 2" > this is the article 2 < / nuxt - link > < / li > < li > < nuxt - link To = "blogs / 3" > this is the article 3 < / nuxt - link > < / li > < / ul > < / div > < / div > < / template >Copy the code

Pages/blogs / _blog. Vue:

<template> <div class="container"> This is the content {{$route.params.blog}} </div> </template> <script> export default {components: { }, data () { return { } }, validate ({ params }) { return ! isNaN(+params.blog) } } </script>Copy the code

The default home page should look like this:

When clicking on a specific article, the following is displayed:


Embedded routines by

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 child view content to the parent component (.vue file).

The staff introduction page uses nested routines. Click the list of personnel on the left, the corresponding personnel information will appear, the effect is as follows:

To do this, we need to add the people introduction page users.vue under Pages

<template> <div class="container"> <div class="bm-sider"> <ul class="players"> <li v-for="user in users" :key="user.id">  <NuxtLink :to="'/users/'+user.id"> {{ user.name }} </NuxtLink> </li> </ul> </div> <div class="bm-con"> <NuxtChild :key="$route.params.id" /> </div> </div> </template>Copy the code

Add a directory with the same name as the file to hold the subview components. The file is named as follows:

├── users │ ├─ ├─ ├.vue ├─ ├─ ├─ vueCopy the code

The users/index. Vue:

<template>
  <h2>Please select an user.</h2>
</template>

Copy the code

The users / _id. Vue:

<template> <div class="player"> <h1>#{{ number }}</h1> <h2>{{ name }}</h2> </div> </template> <script> export default { validate ({ params }) { return ! isNaN(+params.id) }, asyncData ({ params, env, error }) { const user = env.users.find(user => String(user.id) === params.id) if (! user) { return error({ message: 'User not found', statusCode: 404 }) } return user }, head () { return { title: this.name } } } </script>Copy the code

So, when we don’t click on people, the default people profile page looks like this:

After clicking the personnel, the personnel introduction page will display the corresponding personnel information content:

Global CSS

Adding global CSS in Nuxt is also very simple. Let’s create a new CSS file base.css under assets. Then reference it in nuxt.config.js.

  css: [
    '~assets/base.css',
  ],
Copy the code

The global method

Inject content into a Vue instance to avoid repeated import by mounting an injection function on the Vue prototype that is accessible within all components.

plugins/vue-inject.js:

import Vue from 'vue'

Vue.prototype.$myInjectedFunction = (string) => console.log("This is an example", string)

Copy the code

This way, we can use this function in all Vue components.

example-component.vue:

export default {
  mounted(){
    this.$myInjectedFunction('test')
  }
}

Copy the code


conclusion

Nuxt.js is a Vue based SSR framework encapsulated by Webpack and Node.js. With nuxt. js, you can implement a first-screen rendering Web application through its agreed file structure and API without having to build a set of SSR programs yourself. As a whole, Nuxt.js manages our program through the constraints of individual folders and configuration files without loss of extensibility.