当前位置:网站首页>Nuxt. Differences between JS spa and SSR
Nuxt. Differences between JS spa and SSR
2022-06-23 10:08:00 【Black cat crimson】
One 、 introduction
Nuxt.js It's based on Vue.js General application of frame , One for the Vue.js Development SSR One stop solution for application . Its advantage is that the contents of the original configuration files , All integrated into one nuxt.config.js, Encapsulation and extensibility fit perfectly .
In contact with nuxt.js Before , First of all, we need to understand two concepts :Vue Developed client-side single page application (SPA)、 Server rendering framework (SSR)
- SPA: Single page application

Conventional SPA Application is to bundle.js Get... From the server , Then the client parses and mounts to dom On the body .
advantage :
- Fast switching between pages
- Reduce the pressure on the server
shortcoming :
- The first screen loads slowly
- Obviously , It's not good for SEO( Search engine optimization ), Because the crawler can't crawl to the specific html page ( because SPA Most of them are single page components , None of this is html Code form )
Optimize :
- Components / Lazy loading of routes 、 Asynchronous component
- Compress the packaged resources , Reduce inlet pressure
- Compress the packaged resources
- Adopt higher level SSR Server rendering
SSR: Server rendering
It can be understood as : stay node Server Vue Program , Then handle the problem of page rendering in the server , Finally, the page is directly html The presentation of is passed to the client , The client just needs to render ; This greatly reduces the loading time , Improved loading efficiency
namely : Web pages are generated by rendering on the server and then output to the client
stay SSR in , The front end is divided into two parts : Front end client 、 Front end server
Front end server , Used for sending ajax, Get data
Front end client , Is used to ajax Data and pages are rendered , Render into html page , And respond to the caller ( browser 、 Reptiles )
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-BJKLikfk-1655718713231)(../AppData/Roaming/Typora/typora-user-images/image-20220620143009204.png)]](/img/c0/84716ac7a55d551d24f646b0d6014d.png)
If the reptile gets html page , You can start the handler , Process page content , Finalized SEO operation .
Now understand Nuxt.js complete SSR technological process 
- Nuxt Encapsulate the code project program as
- Server Service package
- Client Client package
- Webpack Package these two packages as
- Server bundle.js —— Provide to node Server usage , stay node The server is responsible for data processing , Then get the rendered page ( Can't bind js event , Can only be html+css)
- Client bundle.js —— Receive the pure static of the server html Code , Then proceed
HydrateMix in . At this time, the client'svirtual-domPre render , And the static page returned by the server , Compare whether the rendered content on both sides is consistent . In case of inconsistency, an error will be reportedHydrate.....; If it is consistent, it will affect DOM Element
Two 、 Test server-side rendering
2.1 Set up the project
establish :
npm init nuxt-app <project-name>
Then select the configuration step by step
function :
npm run dev
visit :
http://localhost:3000
Project structure :
| Directory name | describe |
|---|---|
| assets | Resource directory , Used to store static resources that need to be compiled ( Packaged resources ), quote assets Resources can be used ~ or @ Abbreviation form , such as <img src=“~assets/13.jpg”/> |
| components | vue Component catalog ,Nuxt.js This directory will not be enhanced , That is not supported SSR |
| layouts | Layout component Directory |
| pages | Page directory , be-all vue View ,nuxt Automatically generate the corresponding route according to the directory structure . |
| plugins | Plug-in directory |
| static | Static file directory , Files that do not need to be compiled , quote static Resources can be used / Abbreviation form , such as <img src=“/12.jpg”/> |
| server | The server code is written in this folder |
| store | vuex Catalog |
| nuxt.config.js | nuxt Personalization profile , The content will override the default |
| package.json | Project profile |
2.2 Write the server interface
Here I use express To write an interface , The purpose of this interface is to return all student data .
Interface structure :
// All server-side code is placed in server Under the folder
|server/
// Create a specific module folder for an interface
|--| students/
|-----| student_info.js
// index.js be located server Under the root directory of , Be responsible for integrating all interface processing codes
|--| index.js
student_info.js File code :
const express = require('express')
const router = express.Router()
router.get('/info', (req, res)=>{
return res.status(200).json([
{
id: '1902',
name: 'neko_z'
},
{
id: '1903',
name: 'neko_k'
},
{
id: '1904',
name: 'neko_m'
}
])
})
module.exports = router
towards index.js Mount in the file student dependent api Interface :
// Part of the code
const express = require('express')
const consola = require('consola')
const {
Nuxt, Builder } = require('nuxt')
const student = require('./students/student_info')
const app = express()
// Mount routing rules , The first parameter is path , The second parameter is the routing object or callback function
app.use('/api/student',student)
Now let's visit it on the computer http://localhost:3000/api/student/info try , You can find that the data is successfully rendered on the page :

2.3 Write client pages
2.3.1 SPA Rendering
// students Display interface
<template>
<div>
<div
v-for="item in infoList"
:key="item.id"
>
<li>{
{item.id}}</li>
<span>{
{item.name}}</span>
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
// If you don't add a layout property to your page,
// e.g. layout: 'blog', then the default.vue layout will be used.
// You need to add a layout Attributes indicate what pages need to be displayed , Otherwise, the default page will be displayed
layout: 'student',
data() {
return {
infoList: []
}
},
created() {
this.getStudentsList()
},
methods:{
getStudentsList(){
axios.get('http://localhost:3000/api/student/info').then(res=>{
this.infoList = res.data
})
}
}
}
</script>
At this point, we have successfully rendered the data to the page , however , Open the page source code to see : The data on the page does not appear in the page source code
This is because single page applications get data from the server for rendering ,html These data are not available in the file , This example also illustrates why SPA The application is difficult SEO, This is because The crawler cannot crawl to the key data in the page

2.3.2 SSR Rendering
<template>
<div>
<div
v-for="item in infoList"
:key="item.id"
>
<li>{
{
item.id}}</li>
<span>{
{
item.name}}</span>
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
layout: 'student',
data() {
return {
infoList: []
}
},
// Nuxt.js peculiar api, Responsible for asynchronous data processing
// This api Both on the client side , It can also be executed on the server
// Be careful : This method can only be used in page Page usage !
async asyncData() {
let list = await axios.get('http://localhost:3000/api/student/info')
// because Nuxt The life cycle of lies in vue Before , So we can't get through here this.infoList Go and get it vue Properties in
// So this function provides a return value
return {
infoList: list.data
}
}
}
</script>
Now let's look at the web page source code , You will find that the background data is rendered on the page :

Reference article
边栏推荐
- Is there anyone who plans to open source an industrial "seckill" system architecture?
- Unity技术手册 - 生命周期LifetimebyEmitterSpeed-周期内颜色ColorOverLifetime-速度颜色ColorBySpeed
- SQL教程之 5 个必须知道的用于操作日期的 SQL 函数
- xml相关面试题
- Unable to enter the system normally, press F8 to select other items to try to enter
- Install using snap in opencloudos NET 6
- 汇编语言中断及外部设备操作篇--06
- Cloud native database Amazon RDS
- 分布式常见面试题
- Jump game of leetcode topic analysis
猜你喜欢
随机推荐
数值计算方法
Three implementation methods of distributed lock
Sun Tower Technology recruits PostgreSQL Database Engineer
2021-05-12 internal class
Developer, you may have some misunderstandings about cloud computing
2021-05-12内部类
RT thread add MSH command
Gorm 高级查询
XML related interview questions
laravel8 beanstalk 使用说明
大作业合集
Mysql 的Innodb引擎和Myisam数据结构和区别
Golang 快速上手 (1)
2022 gdevops global agile operation and maintenance summit - essence playback of Guangzhou station (with PPT download)
2021-04-16递归
Golang 快速上手 (3)
135,137,138,445禁用导致无法远程连接数据库
Go 单元测试
谷贱伤农,薪贱伤码农!
2021-05-07 constructor









