Vue server rendering principle analysis and introduction

Xiling Laoshi 2021-02-23 04:07:04
vue server rendering principle analysis


The opening

Before we start, we need to figure out a problem : What is server-side rendering ?

In the old concept , Rendering is mostly done on the client side , So why do we let the server do this work now ?

Is there any difference between server rendering and client rendering ?

In fact, there are many tools for server-side rendering , Look at the manual and you'll soon get started , It's not that difficult , The key lies in , What scenarios do we need to use server-side rendering , What kind of rendering scheme is more suitable for our project ; Know what it is , Know why , We need to understand the basic concepts and principles of server-side rendering first , Why does server side rendering appear , What kind of problems have we solved , Master the overall rendering logic and ideas , Only when we use learning tools , Relaxed and comfortable , And even if the tools change and update in the future , We can also be handy , No more “ Learn not to move ” 了 ;

This logic is called Tao 、 Law 、 Technique 、 The concept of the instrument ; Don't just stay in the use of tools and the ingenuity of some tools , More to the law 、 Growth on the level of Tao ;

What is? SSR ?

Modern front end projects , Most of them are single page applications , That's what we're talking about SPA , The whole app has only one page , By means of components , Show different page contents , All the data is obtained through the request server , In the client assembly and display ; This is the default rendering logic of the current front-end framework , We call it : Client rendering scheme ( Client Side Render abbreviation : CSR );

The loading and rendering process is as follows : HTML/CSS Code --> load JavaScript Code --> perform JavaScript Code --> Render page data SPA Client side rendering of the application , There are two big problems :

1: White screen time is too long , Bad user experience ;

2:HTML There's nothing in it ,SEO unfriendly ;

The reason for this problem is , On first load , You need to download the entire SPA Script program , After the browser executes the code logic , To get the data that the page really wants to display , and SPA Script download takes a long time to wait and execute , meanwhile , Download to your browser SPA Scripts have no page data , Browsers don't actually do much rendering , So what users see is a page without any content , More Than This , Because there is no content in the page , The crawler of search engine crawls to the blank content , It's not good for SEO Keyword acquisition ;

Compared to traditional sites , All the pages obtained by the browser are static pages with content processed by the server , Those who have experience in back end programming may be more familiar with it , Page structure and content , It's all processed by the server , Return to the client ;

The first motion picture of the universe , The whole process shows

When we compare them, we find that , Traditional site page data synthesis in the background server , and SPA The page data of the application is synthesized in the browser , But either way , The final rendering , Or leave it to the browser , therefore , Don't get me wrong , What we're talking about here Server rendering and Client rendering , It refers to the work of page structure and data synthesis , It's not the job of browser presentation ;

So can we use the traditional website ideas to solve SPA We can keep the question of SPA What's the advantage of ? Whether it's a long white screen or SEO unfriendly , It's actually the first screen of the page structure, back to the browser , And then get the data and synthesize it , that , First screen page structure and data , Just like a traditional site , First synthesize in the server and then return , At the same time SPA The script is still loaded on the first screen , At this point, the returned page is the complete content of the structure and data , In this way, the browser can display the home page data and load it at the same time SPA Script , Search engine crawlers can also get the corresponding data , solve SEO The problem of ; To better understand this logic , I drew a flow chart :

you 're right , That's what we're talking about The basic logic of server rendering , Server side rendering is SSR (Server Side Rendering) ;

The problem of long white screen time has been solved , Because the first time you load , The server will first return the rendered static page to , Load the request again in the static page SPA Script ;

The basic principle : Home page content and data , Create a static page before the user requests it , Simultaneous addition SPA The introduction of script code , After the browser has rendered the static page , request SPA Script application , After the page interaction is still client rendering ;

Understand the principle , That is to say, to the Tao 、 The realm of law , Next , Let's go down to earth and enter the art of art 、 Feel the application of the device ;

among Vue The framework and React There are corresponding and mature frameworks SSR Solution ,React The corresponding is Next.js frame ,Vue The corresponding is Nuxt.js, Of course , If you're not interested in any of this , You can also achieve one by yourself SSR Server application of , I've written one myself before , If you're interested , Want to see the code I implemented , You can leave me a message , I'll send it back as a tutorial ;

We use Vue Corresponding Nuxt.js For example , To experience the server rendering ;

Nuxt.js application

Nuxt.js It's based on Vue.js The general application framework of .Nuxt.js Preset the use of Vue.js Development Server rendering All kinds of configuration required for the application , Based on Vue.js The application provides the function of generating the corresponding static site . open Nuxt.js Official website :https://www.nuxtjs.cn/ , The study guide is very detailed and easy to understand , According to the guidelines , We can see that there are two ways to install , A kind of use create-nuxt-app Scaffold tools , The other is to create it by hand ;

install

Scaffold installation

Next, let's try different installation methods , Use scaffolding to install first , Carry out orders : npx create-nuxt-app creact-nuxt

next , There are many options on the command line , There are project names 、 development language 、UI Component library 、 Server framework 、 The test framework 、HTTP Request library, etc , You can make different choices according to your own needs , After successful installation , The corresponding prompt information will be given in the command line .

We can follow the message , Run the project , There are two operation modes of the project: development environment and production environment , Use it directly in the development environment npm run dev that will do , To run the production environment , It needs to be done first build compile , The project can only be started after the compilation is successful ;

Because the project was just initialized , We didn't write anything , therefore , No matter which way you run it , All we can see is the following page ;

Manual installation

Unlike scaffolding , Manual installation requires us to create our own projects and install the required extensions and plug-ins , We also need to write our own component code , Then configure the execution command , To start running , however , Manual creation tests the overall control ability of the project ;

Carry out orders : mkdir nuxtnpm After creating the folder , Toggle directory : cd nuxtnpm ;

And then execute the command :npm init -y Create a project and build package.json file ;

Use command :npm install nuxt --save install Nuxt.js frame ;

stay nuxtnpm Directory , establish pages Contents and pages/index.vue Component files , In the component file , Write the following code , Say hello :

<template>
<div>
<h2> hi Nuxt.js </h2>
</div>
</template>
<script>
export default {
}
</script>
 Copy code 

Last , We still have to be in package.json In file , Configure script parameters for running commands :

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

After configuring the command parameters , It's the same as the previous routine :

npm run dev Start a hot loaded Web The server ( Development mode )

npm run build Compile the project , utilize webpack Compile application , Compress JS and CSS resources ( For publishing );

npm run start Start a production model Web The server ( You need to compile the project first ).

After project operation , We can see the content of the component just written ;

It should be noted that ,pages A directory is a must ,Nuxt.js The framework will automatically read all the .vue File and automatically generate the corresponding routing configuration .

route

Basic routing

Basic routing does not need to be configured ,Nuxt.js Will be based on pages The folder and file in , Automatically generated routing configuration

hypothesis pages The directory structure of is as follows :

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

that ,Nuxt.js The automatically generated route configuration is as follows :

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 code 

alike , stay /.nuxt/router.js In file , We can also see the relevant content ;

Route navigation

Nuxt There are three ways of route navigation in , One is ordinary a Tag jump , It's too basic to talk about here , The other two are nuxt-link Component and programmed navigation ,nuxt-link Component is used to add a link to a page and jump to another page , at present <nuxt-link> Function and router-link Agreement , Recommended reading Vue Routing documents To find out how to use it , therefore , you are here Vue How to use , stay Nuxt How to use it in the same way .

And the use of programming navigation , Same as Vue It is used in the same way :

<template>
<div>
<h2>nuxt-link Jump :</h2>
<nuxt-link to="/user/info">Go to user</nuxt-link>
<h2> Programming 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 code 

Dynamic routing

stay Nuxt.js Dynamic routing with parameters is defined , You need to create the corresponding Prefixed with an underscore Of Vue file or Catalog .

Name the name after the underline , But when getting dynamic routing parameters , The name of the file is the keyword to get , Usage and Vue-Router Almost the same :

\pages\user_kk.vue

<template>
<div class="mis">
<h3> Dynamic routing -route</h3>
<!-- To obtain parameters , Print -->
<p> To obtain parameters , Print : {{$route.params.kk}}</p>
<p> The console also has outputs </p>
</div>
</template>
<script>
export default {
mounted(){
// Get route parameters , Console printing
console.log(this.$route.params.kk)
}
}
</script>
<style>
.mis{
background: coral;
}
</style>
 Copy code 

visit :http://localhost:3000/user/3

stay Nuxt.js perform generate On command , Dynamic routing will be ignored ,( I will focus on )

Nested Route

You can go through vue-router Sub route creation of Nuxt.js Nested routes for applications . Create an embedded sub route , Need to add a Vue file , Add a... At the same time With the same name as the document Is used to store subview components . In the parent component (.vue file ) Internal increase <nuxt-child/> Used to display subview content .

Parent component file content

\pages\order.vue

<template>
<div>
<h2> Nested Route </h2>
<!-- Used to display subview content -->
<nuxt-child />
</div>
</template>
<script>
export default {
}
</script>
 Copy code 
Nested subcomponent file and content

\pages\order\index.vue Nested components are displayed by default , Access path : http://localhost:3000/order

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

\pages\order\info.vue Access path : http://localhost:3000/order/info

<template>
<div>
order->info
</div>
</template>
 Copy 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 a request , get data
const { data } = await axios.get(`http://127.0.0.1`);
// Parsing data
const dataObj = JSON.parse(data);
// After returning data ,Nuxt Will merge data Method data to the component , No extra code required
return { dataObj };
},
}
</script>
 Copy code 

Asynchronous data -asyncData

Nuxt.js Expanded Vue.js, Added a name asyncData Methods , It enables us to acquire or process data asynchronously before setting the data of components .asyncData The method will be in the component ( Limited to page components ) Called before each load . It can be invoked before server or routing updates .Nuxt.js Will asyncData The returned data fusion component data The data returned by the method is returned to the current component .

<template>
<div>
user-index page
<hr />
<!-- Traversing display data -->
<div v-for="v in dataObj">
<h3>{{ v.name }}</h3>
</div>
</div>
</template>
<script>
import axios from "axios";
export default {
async asyncData({ params }) {
// Send a request , get data
const { data } = await axios.get(`http://127.0.0.1`);
// Parsing data
const dataObj = JSON.parse(data);
// After returning data ,Nuxt Will merge data Method data to the component , No extra code required
return { dataObj };
},
};
</script>
 Copy code 

Nuxt.js Yes SSG Support for

Before we start , We need to know SSG The meaning of ,SSG(Static Site Generators): Static site generation .

That is, all the pages used in the application , The scheme of generating all static files ; Static site generation scheme , More suitable for CDN、 cache 、 Content data unchanged pages , such as : Flyers 、 Blog posts 、 Help document 、 News page 、 E-commerce product list and many other application scenarios ; Because the pages are made by Mr. Shi , A build , Repeated use , Fast access .

that , stay Nuxt.js How to export the application statically in ?npm run generate The command is used for static export , After this order is executed ,Nuxt According to the routing configuration , Generate the corresponding HTML Static site resources , This command creates a dist Folder , All the static resource files are in it .

I said before stay Nuxt.js perform generate On command , Dynamic routing will be ignored .

Dynamic routing manual configuration

If you want to let Nuxt.js Static files are also generated for dynamic routing , You need to specify the value of the dynamic routing parameter , And configure to routes Go to... In the array .

We can do it in nuxt.config.js In Chinese, it means /users/:id The routing configuration is as follows :

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

Dynamic routing data generation

But if routing Dynamic parameters The value of is dynamic rather than fixed , What should be done ?

You can use a return Promise Object type function , It means , Send a request to get all the data , According to the returned data , Generate all possible routes , And then according to all the routes , Generate all static files

nuxt.config.js

const axios = require('axios')
module.exports = {
generate: {
// Generate routing file , Not the catalog 
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 => {
// Assembly routing 
return '/user/' + user.id
})
})
}
}
}
 Copy code 

Asynchronous data -asyncData And mounted The difference between

mounted In static site generation , Getting data is not executed , Code will be compiled into statically generated JS in , It is executed only when the browser is rendering ,

asyncData When exporting a static site , Can execute code , And compile the data directly into the HTML in , Code doesn't compile to a static file JS in ;

I like it , Don't skimp ;

版权声明
本文为[Xiling Laoshi]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/02/20210223024104481T.html

  1. JavaScript advanced: Javascript object-oriented, JavaScript built-in object, JavaScript BOM, JavaScript encapsulation
  2. JavaScript advanced: Javascript object-oriented, JavaScript built-in object, JavaScript BOM, JavaScript encapsulation
  3. Vue determines whether the El form in the elementui is updated or changed. If it changes, it will prompt whether to save it. If it does not change, it will leave directly
  4. Algorithm problem: sum of two numbers -- JavaScript and Java implementation
  5. High performance nginx HTTPS tuning
  6. JQuery advanced
  7. day 30 jQuery
  8. JQuery:JQuery Basic syntax, jQuery selector, jQuery DOM, comprehensive case check box, comprehensive case random picture
  9. TCP/IP 开胃菜 之 HTTP
  10. JQuery:JQuery Basic syntax, jQuery selector, jQuery DOM, comprehensive case check box, comprehensive case random picture
  11. JavaScript data type
  12. [micro front end] the final chapter of micro front end - Qiankun guide and overall exploration of micro front end
  13. Solve Ajax cross domain problem [5 solutions]
  14. HTTP of TCP / IP appetizer
  15. Optimization of pod creation efficiency in serverless scenario
  16. Iqiyi Sports: experience the ultimate expansion and contraction of serverless, and increase the utilization rate of resources by 40%
  17. First knowledge of HTTP / 1.1
  18. First knowledge of HTTP / 1.1
  19. Webpack learning notes series 05 devserver
  20. Webpack learning notes series 04 - resource processing optimization
  21. How to build a high performance front end intelligent reasoning engine
  22. How to become a professional front end engineer in 2021?
  23. How to transform single / micro service application into serverless application
  24. How to transform single / micro service application into serverless application
  25. How to transform single / micro service application into serverless application
  26. How to connect the ground gas to the micro front end?
  27. How to connect the ground gas to the micro front end?
  28. How to connect the ground gas to the micro front end?
  29. Vue server rendering principle analysis and introduction
  30. Realize the correct loading of text message
  31. Building my own project scaffolding with yeoman
  32. JavaScript advanced prototype and prototype chain
  33. React background management front end system (based on open source framework development) start
  34. JS practical skills breakpoint debugging
  35. I'd like to share with you 20 super easy-to-use Chrome extension plug-ins
  36. Get page element location
  37. Use the powerful API of modern browser to record any interface in the browser and realize export, save and management
  38. Delayed code execution in flutter
  39. Reconfiguration experience of KOA middleware system
  40. Add comments to your blog
  41. Svg editor -- new path
  42. Detailed explanation of debounce and throttle of JavaScript function
  43. Anti shake and throttling and corresponding react hooks package
  44. C2m: the first CSDN article moved to MOOC script 5000 words, detailed painstaking development process, there are renderings and source code at the end of the article
  45. Front end, school recruitment, Taobao, guide
  46. [vue2 & G6] get started quickly
  47. Canvas from the beginning to the pig
  48. Take five minutes to standardize the code comments?
  49. Some thoughts on sass
  50. what?! You haven't filled in the award information yet
  51. How to get the interface + tsdoc needed by TS through swagger
  52. Binary tree
  53. Canvas drawing method in Web screenshot
  54. Front end docker image volume optimization (node + nginx / node + multi-stage construction)
  55. Become a big influence of technology? Coding pages quickly build personal blog
  56. Object and array deconstruction, spread operator, rest operator
  57. Analysis of Axios source code
  58. Two ways to delete useless code in project (Practical)
  59. Edit your picture with canvas
  60. Today's chat: 2-4 years to walk out of the resignation dilemma and comfort zone