preface

If we want to develop news and movie content applications, we need to choose a development framework for SEO and faster loading of server-side rendering.

Nuxt.js was born on demand, and I think it’s more of a solution than a Vue framework, because it would be too quick to get started with Nuxt.js if you had a Vue development foundation. Some of Nuxt’s extensions make me feel more comfortable than Vue development.

Nust. Js is introduced

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.

advantages

  • Based on the Vue. Js
  • Server side rendering
  • Powerful routing function, support asynchronous data
  • Static file service

Nuxt is used for server-side rendering

Instruction is introduced

# Initialization project
npm init nuxt-app <project-name>

# run locally
npm run dev

# packaged
npm run build

# start service
npm run start

Static page generation
npm run generate
Copy the code

The project structure

|-- .nuxt                 // Nuxt automatically generates temporary files for editing, build
|-- assets                // Used to organize uncompiled static resources into LESS, SASS or JavaScript
|-- components            // For Vue components written by yourself, such as scroll components, calendar components, paging components
|-- layouts               // The layout directory, used to organize the layout components of the application, cannot be changed.
|-- pages                 // This is the main area where we work
|-- plugins               // A place to store JavaScript plug-ins
|-- static                // Used to store static resource files, such as images
|-- store                 // Vuex state management for organizational applications.
|-- .editorconfig         // Develop tool format configuration
|-- .eslintrc.js          // ESLint configuration file used to check code formatting
|-- .gitignore            // Configure files that git does not upload
|-- nuxt.config.json      // A personalized configuration for organizing the nuxt.js application overrides the default configuration
|-- package-lock.json     // NPM is automatically generated to help set up the unity of package, and YARN has the same operation
|-- package.json          // NPM package manages configuration files
Copy the code

Commonly used configuration

Change the IP address and port number of the local development operation

// package.js{..."config": {"nuxt": {"host":"127.0.0.1"."port":"1818"}},... }Copy the code

Add for all pages<head>

  // nuxt.config.js

  head: {
    title: 'play-nuxt'.htmlAttrs: {
      lang: 'en'
    },
    meta: [{charset: 'utf-8' },
      { name: 'viewport'.content: 'width=device-width, initial-scale=1' },
      { hid: 'description'.name: 'description'.content: ' ' },
      { name: 'format-detection'.content: 'telephone=no'}].link: [{rel: 'icon'.type: 'image/x-icon'.href: '/favicon.ico'}},Copy the code

Adding a Global CSS

  // nuxt.config.js
  css: ['~assets/css/normailze.css'].Copy the code

Overrides the Loader configuration for Webpack

// nuxt.config.js
build: {
  // Overwrite here
}
Copy the code

Page jump

Use

instead of

<! -- News = vue under pages -->
<nuxt-link :to="{name:'news',params:{newsId:3306}}">NEWS</nuxt-link>
Copy the code

Gets page forward parameters

this.$route.params.newsId;
Copy the code

Default template and layout module

The default template

Create app.html in the root directory, and the content added to that page will be applied to all pages. Where HEAD represents the HEAD configured in nuxt.config.js, and APP represents the Vue component of Pages.

<! -- app.html -->

<! DOCTYPEhtml>
<html lang="en">
  <head>
    {{ HEAD }}
  </head>
  <body>
    <p>What is added to this page is applied to all pages</p>
    {{ APP }}
  </body>
</html>
Copy the code

Layout module

The /layouts folder is a layout module. There are two built-in layout components:

  • /layouts/default.vueThe default layout for all pages
  • /layouts/error.vueError page for 404 or other errors

The layout of the default.vue component is applied to all pages first-layer components that do not have the Layout property set.

<! -- /layouts/default.vue -->

<template>
  <div>
    <p>What is added to this page is applied to all pages</p>
    <! -- <nuxt /> tag indicates current page -->
    <nuxt />
  </div>
</template>
Copy the code

The component error.vue is automatically displayed and passed an error object when the component’s validate method returns false on route 404 or Pages.

<! -- layouts/error.vue -->

<template>
  <div>
    <h2 v-if="error.statusCode==404">404 page does not exist</h2>
    <h2 v-else>500 Server error</h2>
    <ul>
      <li><nuxt-link to="/">HOME</nuxt-link></li>
    </ul>
  </div>
</template>

<script>
  export default {
    props: ["error"]};</script>
Copy the code

When we develop the page, we can use the validate hook to control whether the page is entered or not:

export default {
  validate() {
    // False jumps to layouts/error.vue
    // true displays the page normally
    return false; }};Copy the code

How do I customize the layout? You can also create custom layouts under /layouts.

Start by creating a /layouts/ Custom.vue custom layout component with an optional name

<template>
  <div>
    <nuxt />
    <p>foot</p>
  </div>
</template>
Copy the code

Components under Pages use the Layout property to specify the layout to use

export default{...layout: 'custom'.// Set it to the layout component name. }Copy the code

Set the page switch animation

For all pages

Add the following styles to the global CSS file, such as assets/ CSS /normailze

.page-enter-active..page-leave-active {
  transition: opacity 1s;
}
.page-enter..page-leave-active {
  opacity: 0;
}
Copy the code

Specify page Settings for transition animations

  1. Also adds styles to the global CSS file, but with a different style prefix, used here.testdistance
.test-enter-active..test-leave-active {
  transition: opacity 1s;
}
.test-enter..test-leave-active {
  opacity: 0;
}
Copy the code
  1. Add the following configuration to the corresponding VUE file to realize the transition animation of the specified page
<script>
export default{...transition: 'test'. } </script>Copy the code

Sets the specified page head

Pages components directly use the HEAD hook to override the global HEAD, so that different pages can configure different heads.

<script>
export default{...head() {
    return {
      title: this.title,
      meta: [{ hid: "description".name: "news".content: "This is news page"}}; },... }; </script>Copy the code

Data extension asyncData

AsyncData is used to initialize data asynchronously.

<script>
import axios from 'axios'
export default {
  data(){
     return {
         name:'hello World',}},asyncData(){
      return axios.get('https://api.myjson.com/bins/8gdmr')
      .then((res) = >{
          console.log(res)
          return {info:res.data}
      })
  }
}
</script>
Copy the code

Static resource

Some students will encounter situations where images are available during project development, but not when packaged.

Note that using the ~ identifier to reference static resources does not result in unusable packaging.

<! -- References on HTML tags -->
<div><img src="~static/logo.png" /></div>

<! -- References in CSS -->
<style>
  .diss{
    width: 300px;
    height: 100px;
    background-image: url('~static/logo.png')}</style>
Copy the code

Project deployment

Deployment Mode 1: Deploy it on node to implement server rendering

  1. Add.nuxt, static folder andnuxt.config.jspackage.jsonFiles are copied to the server
  2. An instruction tonpm i -productionnpm run start, and the service can run
  3. Configure the reverse proxy on nginx to run on the corresponding IP address and port

Deployment mode 2: Static page generation

  1. An instruction tonpm run generateThe dist folder, which contains all of Nuxt’s pre-rendered pages, is generated in the root directory
  2. Just drop the DIST content on the server

Two deployment comparison, method one to achieve SSR, first screen rendering fast. Both have good SEO.

After the language

This article will introduce students to nuxt.js. If you want to know more about nuxt.js, go to the official documentation.

Refer to the article

Nuxt.js free video tutorials for jspang

Related articles

Refactoring an existing Vue project to support nuxt.js

Personal scaffolding

My front-end knowledge base, welcome star