Section 1: NuxT.js related overview

Vue.js is used to develop SPA (single page application). Nuxt.js is a framework that uses Vue to develop multi-page applications and complete rendering on the server. The vue project we created can be generated as static HTML directly by command.

1. What are the benefits of server-side rendering?

The main reason is that SPA (single page application) is not conducive to search engine SEO operations, nuxT.js is suitable for news, blogs, movies, consulting, such as the need for search engine traffic provided by the project. If you’re doing mobile projects, there’s no need to use this framework.

2. What is SSR?

Before knowing SSR, a comparison was made between CSR and SSR.

Let’s first look at traditional Web development. In traditional Web development, the client sends a request to the server, the server queries the database, concatenates the HTML string (template), and after a series of data processing, the sorted HTML is returned to the client. The browser is equivalent to opening a page. Such as we often heard of JSP,PHP, ASPX is also the traditional MVC development.

SPA applications, when it comes to Vue and React, the excellent user experience of single-page applications has gradually become the mainstream. The whole page is rendered by javaScript, which is called client-side rendering CSR. SPA rendering process. The client accesses the URL and sends the request to the server, returning the HTML structure (but the HTML structure returned by SPA is very small, with only a basic structure, as shown in the first code). After the client receives the returned result, it starts to render the HTML, executes the corresponding javaScript during rendering, and finally renders the template. After rendering, it sends the data request to the server again. Note that this is the data request, and the server returns the data in JSON format. The client receives the data and completes the final rendering.

SPA relieves pressure on the server, but it has drawbacks:

  1. Long render time for first screen: must waitJavaScriptThe first screen can be rendered only after loading and executing.
  2. SEOUnfriendly: The reptile can only get onedivThe element that thinks the page is empty is not conduciveSEO.

In order to solve the above two problems, SSR solution appeared, the back end rendering out of the first screen DOM structure return, the front end to get the content with the first screen, the subsequent page operation, and then use single page routing and rendering, called server rendering (SSR).

The SSR rendering process is as follows: the client sends a URL request to the server, the server reads the corresponding URL template information, renders THE HTML and data on the server, and returns the HTML structure after rendering. The client then gets the HTML structure of the first screen page. So the user can browse the first screen quickly because the client does not need to send the Ajax request again. It’s not that having SSR doesn’t make our page a SPA app, it’s still a separate SPA app.

SSR is in a compromise between CSR and SPA application scheme, at the time of rendering first screen on the server to make the rendering, attention is only the first screen, other page or need on the client side render, after the server receives the request and render the first screen page, will carry the rest of the routing information reserved for the client to render other routing page.

Nuxt.js is characterized by:

  • Based on theVue
  • Automatic code layering
  • Server-side rendering
  • Powerful routing function, support asynchronous data
  • Static file service
  • EcmaScript6andEcmaScript7Syntax support for
  • Packing and compressionJavaScriptandCss
  • HTMLHeader Tag Management
  • Native development supports hot loading
  • integrationESLint
  • Support for various style precompilersSASS,LESS, etc.
  • supportHTTP/2push

Section two: Nuxt environment construction

1. Nuxt. Js installation

To use NPM you need to install Node into your system. If not installed refer to this link www.cnblogs.com/zhouyu2017/…

(1) Install vue-CLI framework with NPM.

npm install vue-cli -g
Copy the code

After the installation is complete, use vue -v to test whether the installation was successful. (Note: use uppercase V here, lowercase does not work).

(2) Install NUXT using VUE

Once vue-cli is installed, you can use the init command to initialize the nuxt.js project.

vue init nuxt/starter
Copy the code

He’ll download a template on Github and ask you what the name of the project is, the author, whatever you like.

(3) Use NPM install to install the dependency packages

npm install
Copy the code

This process will take a while, but if you fail to install, you can simply remove the node_modules folder from your project and reinstall it from NPM install.

(4) Run the NPM run dev command to start the service

(5) In the browser input localhost:3000, you can see the result, as follows:

2. First Nuxt application installation

npm i create-nuxt-app -g
create-nuxt-app my-nuxt-demo
cd my-nuxt-demo
npm run dev
Copy the code

Installation Wizard:

Use a Custom Server framework // Select features to install // Use a Custom UI Framework // Select the UI framework Use a CustomtestSingle Page App // Render only the current PageCopy the code

3.Nuxt rendering process

A complete server request to render flow

As can be seen from the above flowchart, when a client request enters, the server executes the nuxtServerInit command in the Store action. When receiving the client request, some client information can be stored in the Store. In other words, you can Store the login information of some clients stored on the server to the Store. The middleware mechanism is then used. The middleware is actually a function that is executed before each route is executed. It can do a lot of things here, or it can be understood as the router’s interceptor. Then, when executing validate, the parameters carried by the client are checked. When asyncData and FETCH enter the formal rendering cycle, asyncData obtains data from the server and combines the requested data into data in Vue.

Section 3: Nuxt directory structure

# Introduction to directory structure

├─.nuxt // nuxt Build ├─assets // To organize uncompiled static resources such as LESS, SASS, or JavaScript. For static resource files that do not require Webpack processing, You can also place it in the static directory for your own Vue components, such as the calendar component and the page layout component. Not modify. ⭐ ├─ Middleware // For storing middleware. ├─node_modules ├─pages // For organizing routes and views for applications. Nuxt.js automatically creates route configuration according to the directory structure. File names cannot be changed ⭐ ├─plugins // For organizing Javascript plug-ins that need to be run before the root vue.js application is instantiated. ├─static // For storing static files for applications. Nuxt.js does not call Webpack for build compilation. When the server is started, the files in this directory are mapped to the root path/of the application. The folder name cannot be changed. ⭐ ├ ─store // The folder name cannot be changed. ⭐ ├─.editorConfig // Development Tool Format Configuration ├─.eslintrc.js // ESLint configuration file, For checking code formats.gitignore // Configure Git to ignore files.nuxt.config.js // For organizing the personalized configuration of nuxt.js applications so as to overwrite the default configuration. The file name cannot be changed. ⭐ ├─package-lock.json // NPM automatically generated for unified package Settings. Yarn has the same operation. ├─package.json // NPM Package management configuration fileCopy the code

# Config file

const pkg = require('./package')
module.exports = {
  mode: 'universal'Title: PKG. Name, // title meta: [// meat {charset:'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description'Description}], link: [// favicon, no package for CSS reference {rel:'icon'.type: 'image/x-icon', href: '/favicon.ico' }
    ]
  },
  loading: { color: '#fff'}, // page progress bar CSS: [// global CSS (webPack processing)'element-ui/lib/theme-chalk/index.css'[// plugins'@/plugins/element-ui'], modules: [// modules'@nuxtjs/axios',], axios: {}, build: {// package transpile: [/^element-ui/], extend(config, CTX) {// webPack custom configuration}}}Copy the code

# Nuxt Run the command

{
  "scripts": {// Development environment"dev": "cross-env NODE_ENV=development nodemon server/index.js --watch server", / / pack"build": "nuxt build", // run on the server"start": "cross-env NODE_ENV=production node server/index.js", // generate static pages"generate": "nuxt generate"}}Copy the code

Section 4: Common Nuxt configuration items

1. Set the IP address and port number

In development, it is often encountered that the port is occupied or the IP address is specified. We need to configure the config item in the root directory of package.json. For example, now we want to set IP to 127.0.0.1 and port to 1000.

/package.json

"Config" : {" nuxt ": {" host" : "127.0.0.1", "port" : "1000"}},Copy the code

After the configuration, we type NPM run dev into the terminal, and you will see that the service address is changed to 127.0.0.1:1000.

2. Configure the global CSS

When developing multi-page projects, we define a global CSS to initialize our page rendering, such as padding and margin set to 0. There is also a well-known open source CSS file normailze.css. To define these configurations, you need to operate in nuxt.config.js.

For example, if you want to change the font to red, you can go to assets/ CSS /common.css and change the font to red.

/assets/css/common.css

html{
    color:red;
}
Copy the code

/nuxt.config.js

  css:['~assets/css/normailze.css'],
Copy the code

Enter NPM run dev on the terminal. Then you’ll notice that the font has turned red.

3. Configure the WebPack Loader

The basic configuration of WebPack can be overwritten in nuxt.config.js. For example, we need to configure a URl-loader for 64-bit packaging of small images. This can be configured in the build option of nuxt.config.js, see www.cnblogs.com/ssh-007/p/7…

build: {
    loaders:[
      {
        test:/\.(png|jpe?g|gif|svg)$/,
        loader:"url-loader",
        query:{
          limit:10000,
          name:'img/[name].[hash].[ext]'
        }
      }
    ],
    /*
    ** Run ESLint on save
    */
    extend (config, { isDev, isClient }) {
      if (isDev && isClient) {
        config.module.rules.push({
          enforce: 'pre',
          test: /\.(js|vue)$/,
          loader: 'eslint-loader',
          exclude: /(node_modules)/
        })
      }
    }
  }
Copy the code

4. Modify the SEO head globally

In the nuxt.config.js file, change the title to wfaceBoss:

 head: {
    title: 'wfaceboss',
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: 'Nuxt.js project' }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ]
  },
Copy the code

After the modification, restart the service by running NPM run dev. The effect is as follows

Section 5: Nuxt route configuration and parameter passing

Nuxt.js routing is not complicated, it gives us encapsulation, let us save a lot of configuration.

1. Basic routes

Nuxt.js automatically generates the route configuration of the Vue-Router module based on the Pages directory structure.

Suppose the directory structure of Pages is as follows

├─ pages ├─index.vue ├─ user ├─index.vue ├─one.vueCopy the code

Then, nuxT.js automatically generates the following route configuration:

router: {
  routes: [{name: 'index'.path: '/'.component: 'pages/index.vue'
    },
    {
      name: 'user'.path: '/user'.component: 'pages/user/index.vue'
    },
    {
      name: 'user-one'.path: '/user/one'.component: 'pages/user/one.vue'}}]Copy the code

2. The page is displayed

  1. Do not write a tag, because it is to get a new page, not SPA
  2. <nuxt-link to="/users"></nuxt-link>
  3. this.$router.push(‘/users’)

3. Dynamic routing

  • To define a dynamic route with parameters in nuxt.js, you need to create the corresponding Vue file or directory prefixed with an underscore.
  • {{$route.params.id}}

4. Forward route transfer parameter and value

Routes often need to pass parameters, we can simply use params to pass parameters, we now pass a parameter to the news page, and then the news page will simply receive.

(1) Use nuxt to pass parameters

<template>
  <div>
    <ul>
      <li><nuxt-link :to="`informa/${item.newsCode}-${item.newsType}`"></li>
    </ul>
  </div>
</template>
Copy the code

Note: name refers to a route (folder or file name), and routes are case sensitive, so to is case sensitive. It is recommended that folders be written in lowercase.

(2) Use NUXT to receive parameters

async asyncData(context) {
    let newsCode = context.route.params.code.split(The '-') [0]let newsType = context.route.params.code.split(The '-')[1]
},
Copy the code

$router.push: this.$router.push

$route. push({path: 'route ', query: {key: value}}) In this way, the passing parameter is concatenated after the route and appears in the address barCopy the code

$router.push: this.$router.push

Pass the argument -- this.$router.push({name: 'Name of Route', params: {key: value}}) The value is this.$routeNote: With this method, the parameter is not concatenated after the route, and the parameter will not be seen in the address bar. Note: Since dynamic routes also pass params, this is used.$routerPath cannot be used with params in the.push() method, otherwise params will be invalid. You need to specify the page by name.Copy the code

4. Optimize the URL of project requirements

This.$route.query.key is displayed in the address bar, but is not what we want :id? id=“?

Therefore, it is recommended to use router-link as far as possible to achieve the jump to solve the change of the address bar, which is more convenient to optimize the website

5. Verify route parameters

Nuxt.js allows you to configure a validate method for dynamic routing parameters in the corresponding page component. This function has a Boolean return value. A true return indicates a pass, and a false return indicates a failure.

export default {
  // Nuxt uses the validate method to verify the route parameters. This method must return a Boolean value, where true indicates that the verification is successful and false indicates that the verification fails. Note that validate cannot be written to the Methods property.
  validate(obj) {
    // console.log(obj);
    // return true
    return /^\d+$/.test(obj.params.id)
  }
}
Copy the code

6. Set set by

  1. Add a Vue file as the parent component
  2. Add a folder with the same name as the parent to hold the child view components
  3. In the parent file, add a component that displays the matched child views

Section 6: Nuxt route animation effects

Routing animation, also known as page change effects. Nuxt.js provides two ways to animate routes, one globally and one for individual pages.

1. Global routing animation

By default, global animations are set using pages. For example, we now have an entry and exit fade effect for each page. We can start by creating a normailze.css file under assets/ CSS in the root directory.

(1) Add style files

/ assets/CSS/normailze. CSS (no please set up)

.page-enter-active, .page-leave-active {
    transition: opacity 2s;
}

.page-enter, .page-leave-active {
    opacity: 0;
}
Copy the code

(2) File configuration

Then add a global CSS file to nuxt.config.js.

css:['assets/css/main.css'],
Copy the code

There will be a 2 second animation when the page is switched, but you will find that some pages are not effective because you do not have the

component to make the jump link. You need to make changes.

For example, the dynamically routed news page that we did last time, you need to change it to the link below.

<li><nuxt-link :to="{name:'news-id',params:{id:123}}">News-1</nuxt-link></li>
Copy the code

And then you’ll see the animation.

2. Set the page action separately

To create a special effect for a single page, simply change the default page in the CSS and add the Transition field to the page component configuration. For example, we want to add a zoom in and out effect to the About page, which we don’t have on the other pages.

(1) Add the following to the global style assets/main.css

.test-enter-active, .test-leave-active {
    transition: all 2s;
    font-size:12px;
}
.test-enter, .test-leave-active {
    opacity: 0;
    font-size:40px;
}
Copy the code

(2) Then set it in the About /index.vue component

export default {
  transition:'test'
}
Copy the code

This is where the unique action of page switching comes in.

Summary: import in the page you need to use.

Section 7: Default templates and default layouts for Nuxt

When you’re developing an application, there are common elements that are often used. For example, the title of a web page is the same. Every page has the same title. There are two ways to do this. The first way is to create a common component, and the second way is to modify the default template. Both approaches have their pros and cons. Common components are more flexible, but you need to manually introduce them each time. Templates are convenient, but can only be introduced for each page.

1. Default template

Nuxt provides us with a super simple default template customization method, which can be achieved by creating an app.html in the root directory. Now that we want the words “learn nuxt.js” at the top of each page, we can use the default template to do this.

App. The HTML:


      
<html lang="en">
<head>
   {{ HEAD }}
</head>
<body>
    <p>Learning nuxt. Js</p>
    {{ APP }}
</body>
</html>
Copy the code

{{HEAD}} reads nuxt.config.js and {{APP}} is the main page in the pages folder. Note that both HEAD and APP need to be capitalized. If it’s lowercase, an error will be reported.

Note: If you create a default template, remember to restart the server, otherwise the display will not succeed; The default layout, however, does not require restarting the server.

2. Default layout

The default template has a similar function to the default layout, but as you can see from the name, the default layout is intended to be used for the unified layout of the page. It’s in the layouts/default.vue directory of the location root. It is important to note that there is no header in the default layout, only the content under the

Requirements: Let’s put the words “learn nuxT.js” at the top of each page and see how it is implemented in the default layout.

<template>
  <div>
    <p>Learning nuxt. Js</p>
    <nuxt/>
  </div>
</template>
Copy the code

Here,
is the content of each of our pages. You can also put some common styles into the default layout, but it will add complexity to the page.

Summary: To distinguish the default template from the default layout, the template can be customized with a lot of header information, including IE version judgment; Templates can only customize content in

Section 8: Use of the Nuxt plug-in

1. ElementUI use

  1. Download NPM I element-uI-s

  2. Under the plugins folder, create the elementui.js file

    import Vue from 'vue'
    import ElementUI from 'element-ui'
    Vue.use(ElementUI)
    Copy the code
  3. Add the configuration in nuxt.config.js

    css: [
      'element-ui/lib/theme-chalk/index.css'
    ],
    plugins: [
      {src: '~/plugins/ElementUI', ssr: true }
    ],
    build: {
      vendor: ['element-ui']
    }
    Copy the code

2. The use of axios

  1. The installationnpm install --save axios
  2. use
import axios from 'axios'

asyncData(context, callback) {
  axios.get('http://localhost:3301/in_theaters')
    .then(res= > {
      console.log(res);
      callback(null, {list: res.data})
    })
}
Copy the code
  1. To prevent duplicate packaging, configure it in nuxt.config.js
module.exports = {
  build: {
    vendor: ['axios']
  }
}
Copy the code

Section 9: Nuxt error page and personality meta Settings

A 404 page is essential in application development because we need to give a clear indication when a user enters a routing error. Nuxt.js supports creating error pages directly in the default layout folder.

1. Create an error page

In the layouts folder in the root directory, create an error-vue file, which acts as a component that displays application errors.

<template>
  <div>
      <h2 v-if="error.statusCode==404">404 page not found</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

The code uses v-if to determine the type of error. Note that this error is declared in

Here I also use a

simple method to directly follow the path can be.

2. Personality Meta Settings

The Meta of the page is very important for THE setup of SEO. For example, if you want to make a news page now, in order to collect the news by the search engine, each page needs to have different title and Meta Settings for the news. Use the head method directly to set the header information of the current page. We are now going to set the new-1 page to the meta and title of the personality.

1. Let’s first modify the link of pages/news/index.vue and pass in a title, in order to receive the title on the specific page of the news and form the title of the article.

/pages/news/index.vue

<li><nuxt-link :to="{name:'news-id',params:{id:123,title:'nuxt.com'}}">News-1</nuxt-link></li>
Copy the code

2. After the first step, we modify /pages/news/_id. Vue to make it a unique meta and title tag based on the passed value.

<template>
  <div>
      <h2>News-Content [{{$route.params.id}}]</h2>
      <ul>
        <li><a href="/">Home</a></li>
      </ul>
  </div>
</template>

<script>
export default {
  validate ({ params }) {
    // Must be a number
    return /^\d+$/.test(params.id)
  },
  data(){
    return{
      title:this.$route.params.title,
    }
  },
// Set the head information independently
  head(){
      return{
        title:this.title,
        meta:[
          {hid:'description'.name:'news'.content:'This is news page'}}}</script>
Copy the code

Note: In order to avoid duplication of meta tags in child components that do not properly override the same tags in parent components, it is recommended to use the HID key to assign a unique identifier number to the meta tags.

Section 10: The asyncData method gets the data

Nuxt.js has thoughtfully extended the vue. js method for us, adding anyncData, asynchronous request data.

1. Falsifying data

(1) Create remote data

To make some fake remote data here, the site I chose is Myjson.com, which is a simple JSON repository that is very suitable for learning to use. We open the website and enter the JSON code in the dialog. This code can be entered at will. The key and value are created as strings.

{
  "name": "Nuxt",
  "age": 18,
  "interest": "I love coding!"
}
Copy the code

Enter it and save it. The website will give you an address. This is the address of your JSON repository. api.myjson.com/bins/1ctwlm

(2) Install Axios

The official recommendation of vue. js for remote data retrieval is Axios, so we install the official recommendation to use Axios. Here we use NPM to install Axios. Enter the following command directly into the terminal:

npm install axios --save
Copy the code

2. AnsycData’s Promise method

Let’s create a new file under Pages called ansydata.vue. Then write the following code:

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

At this point, you can see that the browser is already output. The asyncData method returns the value to the data. Is an action taken before the component is created (rendering the page), so you can’t use this.info,

The importance of # return

Be sure toreturnThe data returned here will be merged with the data in the component. This function is executed not only on the server, but also on the client.Copy the code

3. AnsycData Promise concurrent applications

async asyncData(context) {
  let [newDetailRes, hotInformationRes, correlationRes] = await Promise.all([
    axios.post('http://www.huanjingwuyou.com/eia/news/detail', {
      newsCode: newsCode
    }),
    axios.post('http://www.huanjingwuyou.com/eia/news/select', {newsType: newsType, // Information type: 3 EIA information 4 EIA knowledge start: 0, // Start from clause 0 pageSize: 10, newsRecommend:true
    }),
    axios.post('http://www.huanjingwuyou.com/eia/news/select', {newsType: newsType, // Information type: 3 EIA information 4 EIA knowledge start: 0, // Start from article 0 pageSize: 3, newsRecommend:false})])return {
    newDetailList: newDetailRes.data.result,
    hotNewList: hotInformationRes.data.result.data,
    newsList: correlationRes.data.result.data,
    newsCode: newsCode,
    newsType: newsType
  }
},
Copy the code

4. Await method of ansycData

Of course, the above methods are a little outdated, and they all use ANSYc now… Await to solve asynchrony, rewrite the above code.

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

5. Matters needing attention + Life cycle

  1. The asyncData method is called before each load of the component (page component limited)
  2. AsyncData can be called before the server or route is updated
  3. The first parameter is set to the context object for the current page
  4. Nuxt combines the data returned by asyncData with the data returned by the component’s data method
  5. The asyncData method is called before the component is initialized, so the method interior cannot passthisTo reference the instance object of the component

Section 11: Static resources and Packaging

1. Static resources

Download any image from the Internet, put it in the static folder of the project, and then use the following import method to reference it<div><img src="~static/logo.png" /></div>
Copy the code

“~” is the same as locating the project root directory, and the image path will not error, even if the packaging is normal.

(2) CSS to introduce pictures if the introduction of images in CSS, the method and THE direct introduction of HTML is the same, but also with the "~" symbol to introduce.Copy the code
<style>
  .diss{
    width: 300px;
    height: 100px;
    background-image: url('~static/logo.png')}</style>
Copy the code

This is completely normal under NPM run dev.

Pack 2.

Once you’re done with nuxt.js, you can package it as a static file and run it on the server.

In the terminal type:

npm run generate
Copy the code

Then enter live-server in the dist folder.

Bottom line: The NuxT.js framework is very simple because it does most of the work for us, we just need to install its rules to write the code.

Section 12: NuXT’s cross-domain solution + interceptor

Install axios

npm install @nuxtjs/axios --save-dev
Copy the code

Change the configuration information after the installation is complete:

nuxt.config.js

module.exports = {
    modules: [
        // Doc: https://axios.nuxtjs.org/usage
        '@nuxtjs/axios',
    ],
    axios: {
        proxy:true}, axios: {proxy:true,
        prefix: '/api', // baseURL
        credentials: true,
    },
    proxy: {
        "/eia/":"http://192.168.0.97:8181/", // key(prefix) : value(proxy address) changeOrigin:true, // whether to cross domains pathRewrite: {'^/api': ' '// Overwrite the path}}}Copy the code

While we are on the subject of Axios, one of the things I have to mention is interceptors, which are very useful and essential in the development process of a project.

Here’s an example:

The installation

npm install @nuxtjs/axios @nuxtjs/proxy --save
Copy the code
module.expores{
  plugins: [
    {
      src: "~/plugins/axios",
      ssr: false
    },
  ],
  modules: [
    // Doc: https://axios.nuxtjs.org/usage
    '@nuxtjs/axios',]}Copy the code

plugins/axios.js

export default ({ $axios, redirect }) => {
  $axios.onRequest(config => {
    console.log('Making request to ' + config.url)
  })

  $axios.onError(error => {
    const code = parseInt(error.response && error.response.status)
    if (code === 400) {
      redirect('/ 400')}}}export default function (app) {
  let axios = app.$axios; / / basic configuration axios. Defaults. Timeout = 10000 axios. Defaults. Headers. Post ['Content-Type'] = 'application/x-www-form-urlencoded'// Callback axios.onRequest(config => {}) // Return callback axios.onResponse(res => {}) // Error callback axios.onError(error => {})}Copy the code

Section 13: Climb the pit

1. NuxtServerError connect ECONNREFUSED 127.0.0.1:80

/ API /${params.id} = ‘127.0.0.1:80’; / API /${params.id} = ‘127.0.0.1:80’;

Solution:

  1. Change the node server port to 127.0.0.1:80
  2. Change the interface server port to 127.0.0.1:80
  3. Add domain name + port to the request URL used by the asyncData method, as shown below
export default {
  asyncData ({ params }) {
    returnAxios. Get (` https://127.0.0.1:3000/api/${params.id}`)
    .then((res) => {
      return { title: res.data.title }
    })
  }
}

Copy the code

1. How to import JS files into head?

Background: In the tag, the flexibily.js file is imported as inline. This project mainly focuses on mobile terminal project, introducing flexible. Js to realize mobile terminal adaptation.

Nuxt.js uses vue-meta to manage header tags. After viewing the document, you can configure them as follows:

head: {
  script: [{ innerHTML: require('./assets/js/flexible'), type: 'text/javascript', charset: 'utf-8'}],
  __dangerouslyDisableSanitizers: ['script']}Copy the code

2. Nuxt uses preprocessors such as less and SASS

Background: Using various preprocessors in

npm install --save-dev node-sass sass-loader
Copy the code

However, the solution process is not very smooth, when reading the Chinese document, ignore the version number, according to the above prompts to operate, found that it cannot succeed, later various debug, finally found the solution. Later I found that the Version number of the Chinese document is too low. If you need to see the document, you must see the latest version of the English document!

3. How to use Px2REM

Background: In the CSS, write px and use the Px2REM Loader to convert px to REM

In previous projects, this was implemented by px2REM Loader, but under the Nuxt.js project, adding CSS Loader was still laborious because of the vue-loader involved.

An alternative solution has come to mind that can be handled using PostCSS. You can add the configuration in the nuxt.config.js file, or in the postcss.conf.js file.

build: {
  postcss: [
    require('postcss-px2rem')({remUnit: 75 // saves the basic unit})]},Copy the code

4. How to extend the WebPack configuration

Background: Alias the utils directory

As mentioned earlier, Nuxt.js has built-in WebPack configuration. If you want to extend the configuration, you can add it in the nuxt.config.js file. You can also print the configuration information in the file.

extend (config, ctx) {
  console.log('webpack config:', config)
  if(ctx.isclient) {// addaliasThe configuration Object. The assign (config. Resolve. Alias, {'utils': path.resolve(__dirname, 'utils')}}}Copy the code

5. How to add a Vue Plugin

Background: We encapsulate a Toast Vue plugin. Because the vue instantiation process is not exposed, we do not know when to inject it.

You can add plugins configuration to nuxt.config.js so that the plugins are loaded and imported before the nuxt.js application is initialized.

module.exports = {
  plugins: ['~plugins/toast']}Copy the code

~ the plugins/toast. Js file:

import Vue from 'vue'
import toast from '.. /utils/toast'
import '.. /assets/css/toast.css'

Vue.use(toast)
Copy the code

6. How do I modify the environment variable NODE_ENV

Background: In the project, set three NODE_ENV values for different versions. Development C. Release C. Production, online version. The pre-release version has more vconsole than the Production version.

// package.json
"scripts": {
  "buildDev": "cross-env NODE_ENV=release nuxt build && backpack build"."startDev": "cross-env NODE_ENV=release PORT=3000 node build/main.js"
  },
Copy the code

Print process.env.NODE_ENV, production.

The answer is found in the backpack source code, when executing the backpack build command, the process.env.node_env will be changed to production, and is written dead and not configurable……

In process. Env, add an __ENV attribute to represent NODE_ENV

In this case, the information printed in the page is process.env.__env undefined, but process.env.node_env can be printed.

You can solve this problem by configuring the env property in nuxt.config.js.

env: {
  __ENV: process.env.__ENV
}
Copy the code

7. Window or Document object not defined?

Background: When you introduce a third-party plug-in, or write window directly in your code, the console warns that window is undefined.

At the time of this problem, the Node server did not have a Window or document object. The solution is to use process.browser to distinguish between environments.

if(process.browser) {// introduce a third-party plug-in require('* * *'Window.mbk = {}} window.mbk = {}}Copy the code

8. Introduce as needed (UI framework, etc.)

For example, use the UI framework: Element-UI

I looked for a lot of articles about it, but there was no detailed explanation of how to introduce it. So I’m going to take it out and say:

If vendor.js is not introduced as needed, the size of vendor.js is:

Step 1: Download the dependency:

# Download element-ui first

npm install element-ui --save

# Babel-plugin-Component must be installed if you use the on-demand plugin.

npm install babel-plugin-component --save-dev
Copy the code

Once installed, you’ll need to create the plugin file in the plugins/ directory following the rules in nuxt.js

Create (or already exist) a plugins/ directory at the root of the file and create a file named element-ui.js with the following contents:

import Vue from 'vue'

import { Button } from 'element-ui'// Introduce the Buttonexport default ()=>{
    Vue.use(Button)
}
Copy the code

The second step is to introduce plug-ins

In nuxt.config.js, add the configuration: plugins

css:[
'element-ui/lib/theme-chalk/index.css'
],
plugins:[
'~/plugins/element-ui'
]
Copy the code

By default, SSR is enabled and server rendering is adopted. SSR can also be manually configured to be disabled. The configuration is as follows:

css:[
'element-ui/lib/theme-chalk/index.css'
],
plugins:[
    {
        src:'~/plugins/element-ui',
        ssr:false// Turn off SSR}]Copy the code

Third, configure the Babel option

In nuxt.config.js, set the build option to the official website rule:

Build :{Babel :{// Configure import rules as needed"plugins":[
              [
                  "component",
                  {
                      "libraryName":"element-ui"."styleLibraryName":"theme-chalk"
                  }
              ]
          ]
      },
    /*
     ** Run ESLINT on save
     */
    extend (config, ctx) {
      if (ctx.isClient) {
        config.module.rules.push({
           enforce: 'pre'.test: /\.(js|vue)$/,
           loader: 'eslint-loader',
           exclude: /(node_modules)/
        })
      }
    }
 }
Copy the code

At this point, we are observing the size of the file after packaging, as shown in the figure:

At this point, we have successfully completed the import on Demand configuration.

9. Places where you don’t want the server to render

(1) </no-ssr> </no-ssr> (2) nuxt.config.js </ no-SSRfalse
plugins: [
    {src: '~/plugins/ElementUI', ssr: false}].Copy the code

10. Nuxt must add the access domain name before the interface address

Solution: You can use Axios’s baseURL proxy

import Vue from 'vue'
import axios from 'axios'

// axios.defaults.baseURL = "http://www.huanjingwuyou.com/"

axios.defaults.baseURL = "http://localhost:3000/"

// axios.defaults.baseURL = "http://test.huanjingwuyou.com/"

export default axios
Copy the code

Section 14: Nuxt Climb pit update – Judge the device to jump to the mobile end

Nuxt does not have an index. HTML page. Where should we write js code to determine the device? Please see my code below

1. Introduce middleware

  • innuxt.config.jsIn addition to therouterTo introducemiddlewareThe middleware

nuxt.config.jsThe following code

export default {
    router: {
        middleware: ["device",}}Copy the code

2. Create a new directory in the root directoryutilsFile and create a new filedeviceType.js

deviceType.jsThe file code is as follows

/** ** @param {*} UA: userAgent * @returnstype: device type * env: access environment (wechat/weibo /qq) * masklayer: the external to determine whether to display the masklayer, some special environment to guide users to the external to open access */function isWechat(UA) {
    return /MicroMessenger/i.test(UA) ? true : false;
}

function isWeibo(UA) {
    return /Weibo/i.test(UA) ? true : false;
}

function isQQ(UA) {
    return /QQ/i.test(UA) ? true : false;
}

function isMoible(UA) {
    return /(Android|webOS|iPhone|iPod|tablet|BlackBerry|Mobile)/i.test(UA) ?
        true :
        false;
}

function isIOS(UA) {
    return /iPhone|iPad|iPod/i.test(UA) ? true : false;
}

function isAndroid(UA) {
    return /Android/i.test(UA) ? true : false;
}
export function deviceType(UA) {
    if (isMoible(UA)) {
        if (isIOS(UA)) {
            if (isWechat(UA)) {
                return {
                    type: "ios",
                    env: "wechat",
                    masklayer: true}; }if (isWeibo(UA)) {
                return {
                    type: "ios",
                    env: "weibo",
                    masklayer: true}; }if (isQQ(UA)) {
                return {
                    type: "ios",
                    env: "qq",
                    masklayer: true}; }return {
                type: "ios"}; }if (isAndroid(UA)) {
            if (isWechat(UA)) {
                return {
                    type: "android",
                    env: "wechat",
                    masklayer: true}; }if (isWeibo(UA)) {
                return {
                    type: "android",
                    env: "weibo",
                    masklayer: true}; }if (isQQ(UA)) {
                return {
                    type: "android",
                    env: "qq",
                    masklayer: true}; }return {
                type: "android"}; }return {
            type: "mobile"}; }else {
        return {
            type: "pc"}; }}Copy the code

In 3.middlewareadddevice.jsfile

device.jsThe following code

// @ts-nocheck
import { deviceType } from "~/utils/deviceType";
export default function(context) {
    // @ts-ignore
    context.userAgent = process.server ?
        context.req.headers["user-agent"] : navigator.userAgent; DeviceType = deviceType(context.userAgent); // Add a property to the global context to store the matching information we return context.deviceType = deviceType(context.userAgent); // It is injected into the store because some pages need different data to determine the type of request. // It can be removed if you don't use it // context.store.com MIT ("SetDeviceType", context.deviceType); // If UA is not mobile, do it here. // Context.redirect (status, URL); // Context.redirect (status, URL)if (context.deviceType.type === "pc") {
        // context.redirect(302,'www.huanjingwuyou.com') //301 is a permanent redirect, if you want to keep changing with the device type, please change to 302}else {
        context.redirect(302,'m.huanjingwuyou.com') //301 is a permanent redirect, if you want to keep changing with the device type, please change to 302}}Copy the code

Result:

0. Nuxt render page is divided into two stages, server rendering and browser rendering

1. Nuxt can use asyncData in the rendering phase of the server to obtain data in advance. The data is automatically stored in data, and the browser directly takes data when rendering

2. asyncDataMethods will be used in the component (Page Components limited) is called each time when the page is refreshed or the route is switched, in the order before beforeCreate and created

3. There are only two hook functions created and beforeCreate in the lifecycle of nuXT server rendering.

4. Async makes concurrent requests

5. Set head to improve SEO. Return {}

6. The value must be added to the front of the interface each time the interface is invokedAccess to the domain nameCan be configured via Axiosaxios.defaults.baseURL

7. Nuxt uses proxy

8. Skip to the details page with nuxT-link to jump, so the URL address parameters are more conducive to SEO, jump to the time domain name is their own stitching up

9. Write an error page, route call failure or code bug, will jump to the error page

10. Public static pages can be written in assets and then introduced in nuxt.config.js

11. Will be required when publishing online.nuxt.assets.package.json.nuxt.config.js.staticPut the agent in Nginx

BUG

How do I use asynchronous data in a component?

In principle, asynchronous data cannot be used if the component is not a page component bound to a route. Because nuxT.js only extends and enhances the page component’s data method to support asynchronous data processing.

For non-page components, there are two ways to get data asynchronously:

  1. In the component’smountedMethod implements asynchronous fetching logic, and then sets the component data, the limitation is: does not support server rendering.
  2. In the page componentasyncDataorfetchMethod, and treats the data aspropsPass to a child component. Server rendering is working properly. Disadvantages:asyncDataOr the page extract may be less readable because it is loading data from another component. In general, which approach to use depends on whether your application needs to support server-side rendering of subcomponents.

Why does the nuxt.js application page flicker?

This is because in development mode, in order to achieve hot loading via Webpack, CSS code is packaged in JavaScript code and dynamically typed into the page, causing element redrawing to cause flickering.

Don’t worry, in production mode, the CSS code is packaged into a separate file and placed in the head tag, without page flickering.

How do I edit host and port configurations?

Pass it directly as a command argument

nuxt --hostname myhost --port 3333
Copy the code

or

"scripts": {
  "dev": "nuxt --hostname myhost --port 3333"
}
Copy the code

innuxt.config.jsIn the configuration:

In nuxt.config.js add:

export default {
  server: {
    port: 8000, // default: 3000
    host: '0.0.0.0', // default: localhost
  },
  // other configs
}
Copy the code

Use the NUXT_HOST and NUXT_PORT env variables

Similar to HOST and PORT, but more specific, in case you need to add something else.

"scripts": {
  "dev": "NUXT_HOST = 0.0.0.0 NUXT_PORT = 3333 nuxt"
}
Copy the code

Note: For better cross-platform development support, you can use the cross-env dependency package.

Install dependencies:

npm install --save-dev cross-env
Copy the code

Cross – env configuration:

"scripts": {
  "dev": "Cross - the env NUXT_HOST = 0.0.0.0 NUXT_PORT = 3333 nuxt"
}
Copy the code

Use the HOST and PORT env variables

"scripts": {
  "dev": "The HOST = 0.0.0.0 PORT = 3333 nuxt"
}
Copy the code

inpackage.jsonIn the configurationnuxt :

In your package.json file add:

"config": {
  "nuxt": {
    "host": "0.0.0.0"."port": "3333"}},"scripts": {
  "dev": "nuxt"
}
Copy the code