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 ;