Nuxt.js server rendering from installation to deployment

Posted by jimmyt1988 on Thu, 20 Jan 2022 20:31:22 +0100

Nuxt.js server rendering scheme

  • Learn about nuxt Role of JS
  • Master nuxt Routing in JS
  • Master the differences among layouts, pages and components
  • Can be in nuxt Using third-party ui libraries or plug-ins in JS projects
  • Master nuxt How to get data asynchronously in JS
  • Master SEO optimization

1, What is SEO

SEO is the abbreviation of English Search Engine Optimization, which means "Search Engine Optimization" in Chinese. SEO refers to the internal and external adjustment and optimization of the website on the basis of understanding the natural ranking mechanism of the search engine, so as to improve the natural ranking of keywords in the search engine, so as to obtain more traffic and finally achieve the purpose of brand construction or product sales.

2, What is nuxt js

  • SPA (single page web application) is a single page web application. The Web is no longer a page, but an overall application, an application composed of routing system, data system, page (component) system, etc.
  • Vue is the leader in SPA.
  • SPA is widely used in scenarios with low requirements for SEO
  • SEO: search engine optimization (increase collection and weight)
  • SSR: server side rendering
    Split the front end into two parts: client and server
  • Server side rendering is to let the front-end server code execute first, so that the data provided by the back-end can be obtained in advance
  • nuxt.js is based on Vue JS.

3, Why choose it

  • Nuxt.js is based on Vue JS. The main concern is the UI rendering of the application.
  • Nuxt.js preset the use of Vue JS to develop various configurations required for server-side rendering applications.
  • Compared with traditional Vue SPA, using SSR will bring huge SEO improvement, better user experience and more opportunities.
  • Support server-side rendering deployment
  • Support static site deployment

4, How to use

install

For a quick start, nuxt The JS team created the scaffolding tool create nuxt app

npx create-nuxt-app <Project name>
# or
yarn create nuxt-app <Project name>

It will give you some choices:
Choose between integrated server-side frameworks

None (Nuxt Default server)
Express
Koa
Hapi
Feathers
Micro
Fastify
Adonis (WIP)

Select your favorite UI framework

None (nothing)
Bootstrap
Vuetify
Bulma
Tailwind
Element UI
Ant Design Vue
Buefy
iView
Tachyons

Choose your favorite test framework

None (nothing)
Jest
AVA

Select the Nuxt mode you want (Universal or SPA)
Add axios module to easily send HTTP requests to your application.

Add EsLint to check your code for code specifications and errors when saving.

Add Prettier to format / beautify your code when saving.

When it is finished, it will install all dependencies, so the next step is to start the project:

cd <project-name>
npm run dev

::: warning
Note: nuxt JS will listen to the file changes in the pages directory and automatically generate the corresponding route, so there is no need to restart the application or configure the route when adding a new page.
:::

directory structure

└─nuxt-template
  ├─.nuxt               // Nuxt automatic generation, temporary files for compilation, build
  ├─assets              // Used to organize uncompiled static resources such as LESS, SASS, or JavaScript
  ├─components          // For Vue components written by yourself
  ├─layouts             // Layout directory, which is used to organize the layout components of the application
  ├─middleware          // Middleware for storing applications
  ├─node_modules        // Dependent packages
  ├─pages               // Routing and view for organizing applications, nuxt JS automatically generates the corresponding routing configuration according to the directory structure
  ├─plugins             // Used to organize those that need to be in the root Vue Javascript plug-ins that need to be run before JS application instantiation
  ├─static              // It is used to store the static files of the application. Such files will not be used by nuxt JS calls Webpack to build and compile. When the server starts, the files in this directory will be mapped to the root path / directory of the application
  └─store               // Vuex status management for organizing applications
  ├─nuxt.config.js      // Used to organize nuxt JS application to override the default configuration
  ├─package.json        // npm package management profile
  ├─README.md

Page and route

Nuxt.js automatically generates the routing configuration of Vue router module according to the directory structure of pages.
For example, the following directory

└─pages
    ├─index.vue
    └─admin
      ├─index.vue
      ├─user.vue

Automatically generate the following pavement

router: {
  routes: [
    {
      name: "index",
      path: "/",
      component: "pages/index.vue",
    },
    {
      name: "admin",
      path: "/admin",
      component: "pages/admin/index.vue",
    },
    {
      name: "admin-user",
      path: "/admin/user",
      component: "pages/admin/user.vue",
    },
  ];
}

Page Jump

Parameter transfer, dynamic routing and reference Vue router

<nuxt-link to="/admin"></nuxt-link>
this.$router.push("/admin");

layouts & pages & components

  • layouts: the directory of the layout file. The vue file is used for the layout template of the page used. If the page is not specified, the default template is used.
    default.vue template code

    <template>
      <div class="blog-wrap">
        <Nuxt />
      </div>
    </template>
    

    blog.vue template

    <template>
      <div class="default-wrap">
        <Header />
        <div class="default-box">
          <Nuxt />
        </div>
      </div>
    </template>
    <style lang="scss">
    .default-box {
      padding: 20px;
      margin: 20px;
    }
    </style>
    
  • pages: page file. All life cycle functions of vue can be used. You can also use nuxt's proprietary lifecycle functions.
    Use layout to specify the layout template used by the current page

    <template>
      <div class="article-wrap">
        {{ title }}
      </div>
    </template>
    <script>
    export default {
      name: "",
      components: {},
      layout: "blog",
      data() {
        return {
          title: "Here is the page using the template",
        };
      },
    };
    </script>
    <style lang="scss">
    .article-wrap {
    }
    </style>
    
  • Components: the folder where components are stored. Refer to vue's component usage.
    Nuxt is a new feature. The components in this folder will be registered automatically and can be used directly on the page without introduction.

plugins

Nuxt.js allows you to run Vue The js plug-in is executed before the js application. This is especially useful when you need to use your own libraries or third-party modules.
:::warning
It should be noted that in the life cycle of any Vue component, only beforeCreate and created methods will be called on the client and server. Other lifecycle functions are called only on the client side.
:::

If we want to use the vant UI, we need to configure the plug-in before the program runs.

  • Download the plug-in first
npm i vant -S
  • Add the file plugins / vant js
import Vue from "vue";
import Vant from "vant";
import "vant/lib/index.css";

Vue.use(Vant);
  • Then, in nuxt config. The plugins configured in JS are as follows
module.exports = {
  plugins: ["~/plugins/vant"],
};
  • Finally, it is used directly in the page according to the document
<van-button type="primary">Main button</van-button>
<van-button type="info">Information button</van-button>
<van-button type="default">Default button</van-button>
<van-button type="warning">Warning button</van-button>
<van-button type="danger">Danger button</van-button>

Get asynchronous data asyncData

You may want to get and render data on the server side. Nuxt.js adds the asyncData method to enable you to get data asynchronously before rendering components.

The asyncData method is called before each load of the component (limited to page components). It can be called before the server or route update. When this method is called, the first parameter is set as the context object of the current page. You can use the asyncData method to obtain the data and return it to the current component.

:::warning
Note: since asyncData method is called before component initialization, there is no way to reference the instance object of the component through this in the method.
:::

  • Use custom request axios
import axios from "axios";
export default {
  async asyncData({ params }) {
    let { data } = await axios.post(`https://uni.wangcong.wang/uni/article`, {
      action: "getArticle",
      type: "dayRead",
      pagingDto: {
        pageNo: 1,
        pageSize: 100,
      },
    });
    return { list: data.rows };
  },
};
  • Use the built-in @ nuxtjs/axios
//   nuxt.config.js
  modules: [
    '@nuxtjs/axios',
    '@nuxtjs/proxy',
  ],
  axios: {
    proxy: true,
  },
// use
export default {
  async asyncData({ $axios }) {
    let { data } = await $axios.$post(`https://uni.wangcong.wang/uni/article`, {
      action: "getArticle",
      type: "dayRead",
      pagingDto: {
        pageNo: 1,
        pageSize: 100,
      },
    });
    return { list: data.rows };
  },
};

fetch method

The fetch method is used to fill in the application's state tree data before rendering the page. It is similar to the asyncData method, except that it does not set the data of the component.

If the fetch method is set for the page component, it will be called before the component is loaded each time (before the server or switching to the target route).

<template>
  <h1>Stars: {{ $store.state.stars }}</h1>
</template>

<script>
  export default {
    fetch({ store, params }) {
      return axios.get('http://my-api/stars').then(res => {
        store.commit('setStars', res.data)
      })
    }
  }
</script>

For other methods, please refer to the official api document and do not elaborate

SEO configuration

The basic configuration of SEO includes the title, keywords and description of the web page. Nuxt can be configured globally or individually for each page

  • nuxt. config. Configure global head in JS
head: {
    title: 'Website title',
    meta: [
      { charset: 'utf-8' },
      { hid: 'keywords', name: 'keywords', content: 'Keyword 1,Keyword 2' },
      { hid: 'description', name: 'description', content: 'Here is the description of the web page' }
    ]
  }
  • head can also be configured in each page
    Here, you can combine the asynchronous data acquisition method asyncData to set the basic seo information required by the web page in advance

    export default {
      async asyncData({ params }) {
        let { data } = await axios.post(`https://uni.wangcong.wang/uni/article`, {
          action: "articleDetaile",
          _id: params.id,
        });
        return { info: data.rows && data.rows.length ? data.rows[0] : null };
      },
      head() {
        return {
          title: this.info.title,
          meta: [
            { charset: "utf-8" },
            {
              hid: "keywords",
              name: "keywords",
              content: "page A Keyword 1,page A Keyword 2",
            },
            {
              hid: "description",
              name: "description",
              content: "Here is the page A Description of",
            },
          ],
        };
      },
    };
    

    5, Deploy

    Deployment mode

    Nuxt.js provides two ways to publish and deploy applications: server-side rendering application deployment and static application deployment.

    • nuxt start after the server deploys nuxt build
    • Static site deployment nuxt generate
    • You can add these commands to package json:
        "scripts": {
        "dev": "nuxt",
        "build": "nuxt build",
        "start": "nuxt start",
        "generate": "nuxt generate"
        }
    
    • Local packaging, execute npm run build packaging, and upload the following files to the corresponding directory of the server
    • .nuxt
    • nuxt.config.js
    • static
    • package.json
    • package.json indicates that dev is the local startup port and start is the server startup port
    {
      "scripts": {
        "dev": "nuxt --port 3006",
        "build": "nuxt build",
        "start": "nuxt start --port 3006",
        "generate": "nuxt generate"
      }
    }
    
    • Static application deployment
      Nuxt.js can make the application static according to the routing configuration, so that we can deploy the application to any static site host service provider.
    npm run generate
    

    This command will create a dist folder in which all static resource files are located.

    :::warning
    Note: when using nuxt generate to statically apply, the context object passed to asyncData() and fetch() methods will not contain req and res attributes
    :::

    Reference can be made to the following documents

Topics: Javascript Front-end Vue