preface

The first two we in turn from the development of the Web to understand the characteristics of SSR, but also know the true implementation of SSR principle and the whole process, and we take Vue as an example, the completion of Vue based on isomers development and application, today is the last part of SSR, we will carry out the nuxT.JS framework practice

PS: VUE-SSR will be divided into three parts: understanding SSR and practice in Vue (part 1), isomic development of SSR application in Vue (Part 2), nuxt.js practice (part 2)

What is Nuxt. Js

Nuxt.js is a general application framework based on vue.js. By abstracting the organization of the client/server infrastructure, Nuxt.js focuses on the UI rendering of the application.

Conclusion:

  • Nuxt is not only used for server-side rendering but also for SPA application development;
  • Using nuXT’s basic project structure, route generation, middleware, plug-ins and other features can greatly improve development efficiency
  • Nuxt can be used to static web sites

PS: www.nuxtjs.cn/guide (Official documentation…

The characteristics of Nuxt. Js

Nuxt.js rendering process

Nuxt.js applies a complete process of server requests to render (or the user renders the page by switching routes) :

Next, we will practice the nuxt.js feature modules separately

1. Installation of NUXT

Install us using the official provided CLI

NPX create-nuxt-app < project name >Copy the code

This is an optional configuration item in the installation, which can be selected as appropriate for your project needs:

Operating Projects:

npm run dev
Copy the code

We should then see something like this in the browser, indicating that we have successfully installed:

2. Project structure

Let’s take a look at the official generated project structure and briefly look at the role of each folder:

Directory structure:

  • Assets: Asset directory Assets are used to organize uncompiled static resources such as LESS, SASS, or JavaScript
  • Components: Component directory Components are used to organize vue.js components of an application. Nuxt.js does not extend and enhance vue.js components in this directory, that is, they do not have the asyncData method features of page components.
  • Layouts: Layouts are used to organize the layout components of your application.
  • Middleware: Middleware directory used to house the middleware of an application
  • Pages: Pages directory The pages are used to organize routes and views of applications. The nuxt.js framework reads all.vue files in this directory and automatically generates the corresponding routing configuration. (PS: The path after the new file is automatically generated, see the specific example below)
  • Plugins are used to organize Javascript plug-ins that need to be run before the root vue.js application can be instantiated.
  • The static directory is used to store application static files. These files are not built and compiled by nuxt.js calling Webpack. When the server starts, files in this directory are mapped to the root/of the application.
  • Store: a Vuex state tree file used to organize applications. The nuxt.js framework integrates Vuex state tree configurations, which can be activated by creating an index.js file in the Store directory.
  • Nuxt.config. js: This file is used to personalize the NUxT application.

Nuxt.js: Nuxt.js: Nuxt.js: nuxt.js: Nuxt.js: Nuxt.js: Nuxt.js

routing

1. Automatic routing configuration

  • Based on the routing

We will start with a very convenient feature, which is not available in the normal VUE project structure. We all know that we usually use VUe-CLI development, we need to configure the route after creating a new file in Pages. It is a bit troublesome when the project is too big, but our nuxt.js has introduced automatic route configuration

When we create a new file in Pages, the routing structure is automatically configured. Let’s give it a try

Create two. Vue files in Pages:

  • Pages /admin.vue Merchandise management page
  • Pages/login. Vue login page

Then we do nothing, enter the URL in the middle of the browser directly: http://localhost:3000/admin we look at the picture: magic, configuration, nothing routing automatically has been configured, whether the feeling is very sweet!

So where does this route configure itself? Alas, we go to the file structure where all routes are automatically configured:

  • Dynamic routing

We might think that simple routes can be generated automatically, but what if we are dynamic routes? So how do you do that?

In nuxt.js, you need to create a Vue file or directory prefixed with an underscore (_)

Here’s an example:

Let’s take a look at these three pictures, we add folders according to the rules, the result in the routing table is also automatically added to the dynamic route we want, is not very convenient?

  • Embedded routines by

And then we say, well, what if we have nested rules in our project? So how do you do that?

Nuxt.js also takes into account the following rules: to create inline child routing, you need to add a Vue file and a directory with the same name as that file to store the child view components

Let’s also take an example 🌰 :

We see this, it will also be more convenient to automatically generate nested routines by the problem, have to say, this kind of development experience is really good, and according to certain rules to name the file name also helps us to manage the file structure

To add routing navigation, add a code to your layouts/default.vue file:

<template>
  <div>
    <nav>
      <nuxt-link to="/">Home page</nuxt-link>
      <nuxt-link to="/admin">management</nuxt-link>
      <nuxt-link to="/cart">The shopping cart</nuxt-link>
    </nav>
    <Nuxt />
  </div>
</template>
Copy the code

Does it look familiar? Yes, it is similar to the traditional vUE developed router-link, but here we are using SSR mode, so we still choose NUxT-Link for navigation

In PS: layout, default.vue is the default global layout component

We learned how to implement dynamic routing in Nuxt, so let’s think about how to implement custom routing. In other words if I have a page now and I want to use my custom route name what do I do? Ennnn, yes we can, but we need to do it in a more sophisticated way.

We find nuxt.config.js, and we add code to it:

Then we can use our custom routing configuration (although it doesn’t seem to be very useful).

view

Let’s take a look at the layout section of Nuxt. Let’s start with a diagram that shows how nuxt.js configures data and views for a given route

1. Default layoutThe default layout is already mentioned in the layouts/default.vue tutorial at the start of the project

We can also customize our layouts. For example, we want to create a blank page called layouts/blank.vue for login.vue

To start, create a new blank.vue inside your layouts

<template>
  <div>
    <h1>hello, welcome to login</h1>
    <Nuxt />
  </div>
</template>
Copy the code

Then we use it in pages/login.vue

<template>
  <div>The login page</div>
</template>
<script>
  export default {
    layout: 'blank'
  }
</script>
Copy the code

Let’s look at the results:

3. Customize error pagesIn Nuxt, you can easily customize error layouts/error.vue:

<template>
  <div class="container">
    <h1 v-if="error.statusCode === 404">Page does not exist</h1>
    <h1 v-else>Application error exception occurred. Procedure</h1>
    <p>{{ error }}</p>
    <nuxt-link to="/">The first page</nuxt-link>
  </div>
</template>
<script>
export default {
  props: ["error"].layout: "empty"
};
</script>
Copy the code

Let’s take a look at the results:

4, pagePage components are Vue components, but nuxt.js adds some special configuration items to these components, such as title and meta to the home page, index.vue:

export default {
  head() {
    return {
      title: "Course List".// Vue-meta Uses hid to determine the meta to be updated
      meta: [{ name: "description".hid: "description".content: "set pagemeta"}].link: [{ rel: "favicon".href: "favicon.ico"}}}}],Copy the code

Let’s take a look at the results:

Nuxt.js provides customized special configuration for the page. For details, see the official website:

Asynchronous data acquisition

The asyncData method allows us to asynchronously fetch or process component data before setting it up. PS: Those of you who read the previous article will be familiar with this method

Let’s put this into practice with an example:

1, install dependencies, we use KOA as an example to write the server interface:

npm i koa-router koa-bodyparser -S
Copy the code

2. Write server-side scripts

const Koa = require('koa');
const app = new Koa();
const bodyparser = require("koa-bodyparser");
const router = require("koa-router") ({prefix: "/api" });

const goods = [
  { id: 1.text: "iphone12".price: 1000 },
  { id: 2.text: "guangying".price: 1000}];// Configure the route
// Get the product list
router.get("/goods".ctx= > {
  ctx.body = {
    ok: 1,
    goods
  };
});

// Parse the POST data and register the route
app.use(bodyparser());
// Register the route
app.use(router.routes());
app.listen(3030.() = > console.log('API service started'))
Copy the code

3, integrate Axios module first install dependencies:

npm install @nuxtjs/axios -S
Copy the code

Then configure nuxt.config.js:

modules: [
  '@nuxtjs/axios',].axios: {
  proxy: true
},
proxy: {
  "/api": "http://localhost:3030"
},
Copy the code

4, test code, index.vue:

export default {
  async asyncData({ $axios, error }) {
    const { ok, goods } = await $axios.$get("/api/goods");
    if (ok) {
      return { goods };
    }
    // Error handling
    error({ statusCode: 400.message: "Data query failed"}); }}Copy the code

Let’s start the server and look at the results of our test:

State management Vuex

If there is a Store directory in the application root directory, nuxt. js will enable the vuex state tree. When defining each state tree, you can export state, mutations, getters, actions

Take user login as an example, create store/user.js:

export const state = () = > ({
  token: ""
});
export const mutations = {
  init(state, token){ state.token = token; }};export const getters = {
  isLogin(state) {
    return!!!!! state.token; }};export const actions = {
  login({ commit, getters }, u) {
    return this.$axios.$post("/api/login", u).then(({ token }) = > {
      if (token) {
        commit("init", token);
      }
      returngetters.isLogin; }); }};Copy the code

Then we write the logon logic in pages/login.vue:

<template>
  <div>
    <h2>The user login</h2>
    <el-input v-model="user.username"></el-input>
    <el-input type="password" v-model="user.password"></el-input>
    <el-button @click="onLogin">The login</el-button>
  </div>
</template>
<script>
export default {
  data() {
    return {
      user: {
        username: "".password: ""}}; },methods: {
    onLogin() {
      this.$store.dispatch("user/login".this.user).then(ok= > {
        if (ok) {
          const redirect = this.$route.query.redirect || "/";
          this.$router.push(redirect); }}); }}};</script>
Copy the code

Then our logon logic is complete!

The middleware

Middleware runs functions we define before a page or group of pages are rendered, often for permission control, validation, and so on.

For example, we can use middleware to check whether we are logged in or not. If not, we can redirect to the login page. We can write middleware and create middleware/auth.js:

export default function({ route, redirect, store }) {
  Global state in vuEX is accessed through store in this context
  // Determine whether to log in by checking whether the token exists in vuEX
  if(! store.state.user.token) { redirect("/login? redirect="+ route.path); }}Copy the code

All we have left to do is register the middleware, in two ways:

  • Nuxt.config.js implements global registration middleware, which is used globally and is useful for every page accessed.
router: {
    middleware: ['auth'],},Copy the code
  • Local registration middleware, this way is on-demand registration, which page needs to be registered in which page on the line, registration is such as in admin.vue:
export default {
  middleware: ['auth']}Copy the code

The plug-in

Nuxt.js executes plug-in functions before running the application, which is especially useful when you need to introduce or set up Vue plug-ins, custom modules, and third-party modules

Plugins /interceptor.js provide a simple plugin that adds a request interceptor token and creates plugins/interceptor.js:

export default function({ $axios, store }) {
  //onRequest is a help method provided by the @nuxtjs/axios module
  $axios.onRequest(config= > {
    // Append the token
    if (store.state.user.token) {
      config.headers.Authorization = "Bearer " + store.state.user.token;
    }
    return config;
  });
}
Copy the code

We also need to register the plugin in nuxt.config.js:

plugins: ["@/plugins/interceptor"]
Copy the code

This allows us to use the plugin every time we need a network request

nuxtServerInit

By defining the nuxtServerInit method in the root module of the Store, nuxt.js calls it with the page context object passed to it as the second argument. This is useful when we want to transfer some data from the server to the client.

  • NuxtServerInit can only be written in store/index.js
  • NuxtServerInit is executed only on the server side

For example, if we want to initialize the login state in this example, we can do it in store/index.js:

export const actions = {
  nuxtServerInit({ commit }, { app }) {
    // Note that this app is a server instance, in our case the KOA instance
    const token = app.$cookies.get("token");
    if (token) {
      commit("user/init", token); }}};Copy the code

But before we can run it we need to install a dependency:

npm i -S cookie-universal-nuxt
Copy the code

Then register in nuxt.config.js:

modules: ['@nuxtjs/axios'.'@nuxtjs/proxy'."cookie-universal-nuxt"].Copy the code

Several features that will be involved in the development process are basically over! Now that you look back at the nuxT rendering flowchart, doesn’t it make a lot of sense?

Release deployment

1. Server side rendering application deployment: compile and build first, and then start Nuxt service

npm run build
npm start
Copy the code

The location of the content generated by packaging is shown in the figure:

2,Static Application Deployment: nuxt.js can statically configure the application based on the routing configuration, allowing us to deploy the application to any static site hosting service.

npm run generate
Copy the code
  • Note that both the render and interface servers need to be started before executing the command
  • Generate content in dist (root, not the same as the previous approach)

The benefits of this approach is that he will be all the pages in the packing process will be packaged into a static HTML page, so in fact, when we open the URL we actually access is a static page, we can think that not every time apply colours to a drawing, so that when we visit the efficiency will be a huge promotion!

OK, the last Vue SSR article is over ~

This article we mainly learned Vue SSR out of the box program Nuxt.js, we analyzed the basic core content of Nuxt, the rest of the specific there are more points we need to slowly dig later, well, Vue SSR series basically has ended, after three articles down, I believe we should have some understanding of SSR related things ~

At the end of the article

Welcome to pay attention to the “front-end light and shadow” public account, the public account is in the form of the system thematic module to show, so it looks more convenient, system, let us continue to learn all kinds of front-end knowledge, come on!