Front-end Framework Vue (17) - Server-side Rendering (ssr) Universal Application Framework Nuxt.js Based on Vue.js

Keywords: Attribute Javascript github Vue

This article aims to answer three questions through a small demo: 1. What is Nuxt. js? 2. How to enable a Nuxt.js project. 3. How to build a general ssr project.

I. Friendship Links

1,Nuxt.js official website
2,Github(Nuxt.js)
3,Refer to Demo (nuxt-demo)
4,Learning videos (YouTube needs to turn over walls)

2. What is Nuxt.js

If you are using React, you must know that the server side of React renders the application framework Next.js. The same Vue.js-based Nxt.js is also used for server-side rendering.

We know the popular client-side rendering method of web development, SPA (single page web application) single page application. We just need an index.html and a static folder that contains all kinds of static resources. Page jumps are routed and everything is in an app.js file.

This leads to the shortcomings of single page: 1. slow loading of the first screen and white screen. 2. Not conducive to SEO.

Here's why we need a server-side rendering framework like Nuxt.js. The emergence of Nuxt effectively solves the above two problems of single page rendered by client.

  For more information, please refer to the official documents.

Let's look at the intuitive differences in client/server rendering:

URL:

  Client: http://localhost:8080/#/findMusicComponent
  Server: http://localhost:3000/recipes/2

The gap between paths is reflected in #.

Recommended articles: https://segmentfault.com/a/1190000007238999

source code:

  Client:
  <body><div id="app"></div><!-- built files will be auto injected --><script type="text/javascript" src="/app.js"></script></body>

  Server:
  <body data-n-head=""><div data-server-rendered="true" id="__nuxt"><div class="nuxt-progress" style="width:0%;height:2px;background-color:#3B8070;opacity:0;"></div><div id="__layout"><div><header data-v-46cf1d15><nav data-v-46cf1d15><ul data-v-46cf1d15><li data-v-46cf1d15><a href="/" class="nuxt-link-active" data-v-46cf1d15>Starting Page</a></li><li data-v-46cf1d15><a href="/recipes" class="nuxt-link-active" data-v-46cf1d15>Recipes</a></li><li data-v-46cf1d15><a href="/About" data-v-46cf1d15>About</a></li></ul></nav></header><section class="single-recipe"><h1>Delicious vigetable</h1><div class="recipe-image"><img src="https://images.pexels.com/photos/5938/food-salad-healthy-lunch.jpg" alt="Awesome vigetable"></div><p>This is a awesome vigetable</p></section></div></div></div><script type="text/javascript">window.__NUXT__={"layout":"default","data":[{"recipe":{"id":"2","title":"Delicious vigetable","previewText":"Awesome vigetable","descriptionText":"This is a awesome vigetable","thumbnail":"https:\u002F\u002Fimages.pexels.com\u002Fphotos\u002F5938\u002Ffood-salad-healthy-lunch.jpg"}}],"error":null,"state":{},"serverRendered":true};</script><script src="/_nuxt/manifest.js" defer></script><script src="/_nuxt/layouts_default.js" defer></script><script src="/_nuxt/pages_recipes__id_index.js" defer></script><script src="/_nuxt/vendor.js" defer></script><script src="/_nuxt/app.js" defer></script></body>

From source code body Difference, you can see why client rendering mode of single page is not conducive SEO,Very little content, not friendly to browser crawlers.

Recommended articles: https://segmentfault.com/q/1010000009369779/a-1020000009370048

How to start a Nuxt.js project

First of all, before reading this article, I think you have installed Node and NPM, and have a certain Vue foundation.

Two methods:

The first is:

1,npm install create-nuxt-app

2,create-nuxt-app your-app-name


You can return all the way.

3. After initialization, we will get such a directory structure:

What does each folder represent? Refer to official documents.

4. Record the information we need in package.json. Start our demo with npm run dev

{
  "name": "recipes",
  "version": "1.0.0",
  "description": "My outstanding Nuxt.js project",
  "author": "allen",
  "private": true,
  "scripts": {
    "dev": "nuxt",
    "build": "nuxt build",
    "start": "nuxt start",
    "generate": "nuxt generate"
  },
  "dependencies": {
    "nuxt": "^1.0.0"
  },
  "devDependencies": {
    "cross-env": "^5.0.1"
  }
}

Second species:

You need to install the official scaffolding of vue-cli, which is given in the lazy method document for reference in screenshots.

Open localhost:3000, if you go to the next screenshot stage, then congratulations, you can officially develop!

4. How to build a general ssr project

Let's start with a screenshot of demo.

General structure: three first-level columns (start page, menu bar, about page) and one second-level menu (details page of each dish).

Here I want to talk about how dynamic routing implements jumping detail pages according to the ID parameters of dishes. This is consistent with our usual thinking: first, in the menu bar, click on a dish, get the corresponding id, then jump to the details page, asynchronous request to the server, get the corresponding ID dish details, and finally data rendering in the front.

The effect we need to achieve can be reflected in the URL:

  Menu bar: http://localhost:3000/recipes
  Vigetable: http://localhost:3000/recipes/2
  Pizaa: http://localhost:3000/recipes/1

There is such a section on the official network for dynamic routing:

ok, now I'll create a catalogue with the following underlined details:

*_id is the detail directory, and index.vue in all directories is the default home page.

Details page source code:

/**
 * @Description: recipe
 */
<template>
  <section class="single-recipe">
    <h1>{{ recipe.title }}</h1>
    <div class="recipe-image">
      <img :src="recipe.thumbnail" :alt="recipe.previewText">
    </div>
    <p>{{ recipe.descriptionText }}</p>
  </section>
</template>

<script>
export default {
  /**
   * @description data from server
   */ 
asyncData (context) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve({
        recipe: [{
          id: '1',
          title: 'Delicious Pizza',
              previewText: 'Awesome Pizza',
              descriptionText: 'This is a nice Pizza',
              thumbnail: 'https://static.pexels.com/photos/326278/pexels-photo-326278.jpeg'
              },
          {
          id: '2',
          title: 'Delicious vigetable',
              previewText: 'Awesome vigetable',
              descriptionText: 'This is a awesome vigetable',
              thumbnail: 'https://images.pexels.com/photos/5938/food-salad-healthy-lunch.jpg'
          }].find(el => el.id === context.params.id)
        });
      }, 1500)
    })
  }  
}
</script>

<style>
.single-recipe
{
  display: flex;
  flex-flow: column;
  justify-content: center;
  align-items: center;
  text-align: center;
  padding: 30px;
}
.recipe-image img
{
  width: 80%;
}
</style>

The key point is context.params.id, which is the ID of each dish. Here is the new Promise asynchronous request data. Formally, you request the only detailed data under the ID in the background by getting the ID.

Take a look at the router.js section built under dynamic routing:

CONCLUSION: As long as the routing specification provided by Nuxt.js is followed, the page routing switch will be very easy.

Finally, send out the full Demo on Github: Refer to Demo (nuxt-demo)

Concluding remarks: I hope my article will let you know something about Nuxt.js, or start to know Nuxt.js. The article is relatively shallow. If you want to apply server rendering to projects in the future, you need to read the official documents in detail.

Posted by schlag on Tue, 18 Dec 2018 12:39:04 -0800