当前位置:网站首页>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

 Insert picture description here

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)]

    • 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
 Insert picture description here

  1. Nuxt Encapsulate the code project program as
    • Server Service package
    • Client Client package
  2. 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 Hydrate Mix in . At this time, the client's virtual-dom Pre 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 reported Hydrate.....; 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”/>
componentsvue 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
storevuex Catalog
nuxt.config.jsnuxt 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 :

 Insert picture description here

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

 Insert picture description here

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 :

 Insert picture description here

Reference article

Nuxt Detailed explanation + Case study

原网站

版权声明
本文为[Black cat crimson]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206230951594146.html