Class 00: Course Introduction

Nuxt.js is simply a generic framework for vue.js, most commonly used for SSR (server-side rendering). Vue. Js was originally developed for SPA (single-page applications), but with the popularization of technology, many people want to develop multi-page applications with Vue and complete rendering on the server side. At this time, the nuxt.js framework appeared, she simplified the difficulty of SSR development. We can also generate static HTML from our vUE projects directly by command.

So what are the benefits of server-side rendering?

The main reason is that SPA (single page application) is not conducive to SEO operations of search engines. Like you as a news site, traffic is a major source through these search engine baidu, Google, bing, but they are fetching for SPA is not good, especially the baidu can’t crawl to the SPA the content of the page, so we must put our application on the server to render pages for search engines crawl, then downloaded to the client. Nuxt.js is suitable for news, blogs, movies, and consulting projects that require traffic from search engines. There is no need to use this framework if you are working on a mobile project. (Actually nuxt.js personally feels like a solution)

If you’re a Vuer (Vue programmer) and you don’t have the framework, your skills aren’t fully lit up, so spend 10 minutes a day and follow the technical fat to light up your skills.

What is SSR?

SSR, also known as server rendering, is to render the Vue page on the server side to generate HTML files and pass the HTML page to the browser.

SSR has two advantages:

  • SEO is different from SPA HTML, which has only one HTML with no actual content and one app.js. SSR generated HTML has content, which allows search engines to index the page content.
  • Faster content arrival Time Traditional SPA applications fetch bundle.js from the server, parse it on the client side and mount it into the DOM. SSR passes the HTML string directly to the browser. Greatly speed up the first screen load time.

The official nuxt.js website says:

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.

Nuxt.js features (advantages) :

  • Based on the Vue. Js
  • Automatic code layering
  • Server side rendering
  • Powerful routing function, support asynchronous data
  • Static file service
  • ES6/ES7 syntax support
  • Package and compress JS and CSS
  • HTML header tag management
  • Local development supports hot loading
  • Integrated ESLint
  • Support for various styles of preprocessors: SASS, LESS, Stylus, and more

Course Description:

The course will be in the form of an essay and a video. You can watch the video first, and the essay will be used as a record of your study when typing code or reviewing.

The videos are updated two or three times a week (I’m not a full-time lecturer, I’m a front-line coder, and I can only record them when I get home).

This course is free to watch, and there is no advertisement on the blog. If you find it helpful to you, please scan the code on the right side to reward, so as to maintain the livelihood of the station.

Learn what you need:

Be familiar with the basics of HTML+CSS, JavaScript and Vue.

Vue basic knowledge complete set link address

If you’ve already done one or two Vue projects, that’s great. If you haven’t, don’t be discouraged. I’ll take care of my new friends, slow down and explain more code.

Section 01: Nuxt Environment setup and Hello World

If you’ve found this course, you’re familiar with SSR. You’ve already talked about SSR in the course introduction, so I’m going to jump right into using nuxt.js. In this section, we will install the development environment and create a simple Hello World.

Nuxt. Js installed

You need to install Node into your system before using NPM. If you don’t already know how to install Node, skip this tutorial and start with the technical basics of Vue.

1. Use NPM to install vuE-CLI. If you have already installed it, skip this step.

npm install vue-cli -gCopy the code

This depends on your network environment, the installation speed is not only the same, if your network environment is really bad, you can consider using CNPM to install. (IN real development I try to avoid using CNPM for installation because of unknown errors.)

After the installation is complete, you can use vUE -v to test whether the installation is successful. (Note: use uppercase V here; lowercase will not work).

2. Use vUE to install NUXT

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

vue init nuxt/starterCopy the code

He will download the template on Github and ask you for the name of the project and the author. Fill in the template according to your own preferences.

3. Use NPM install to install dependency packages

npm installCopy the code

This process can take a while, but if you fail to install this process, don’t panic. You can simply delete the node_modules folder in your project and reinstall NPM install.

4. Run NPM run dev to start the service

npm run devCopy the code

5. Enter localhost:3000 in the browser. The result is displayed.

Hello World

Hello, everybody. Hello, everybody. Hello, everybody.

Find the /pages/index.vue file in the project root directory and change the project name to Hello World. The framework supports hot updates, so you automatically update without refreshing.

(Please watch the video for specific operation steps, I will not give you screenshots)

Summary: This lesson is very simple, but pay attention to your network environment, don’t be discouraged if the installation fails, delete node_modules and try again. Start work quickly follow technology fat to do, do not make you can’t learn.

Section 02: Nuxt directory structure in detail

Last time we installed the development environment successfully, this time we will go through the purpose of each folder and file, and give a detailed introduction to status files.

Directory structure:

Nuxt automatically produces project catalogs, so let’s take a look at them one by one.

. | - nuxt / / nuxt automatically generated, temporary to edit the file, build | - assets / / used to organize not compile static resources into LESS, SASS, or JavaScript | - components / / used to write your own Vue components, Such as rolling components, calendar component, paging component | - layouts / / directory layout, the layout of the application used to organize components, may be changed. | - middleware / / to hold middleware | - written pages / / to hold page, our main work area | - plugins/where/to hold JavaScript plugin | - static / / to hold static resource file, Such as picture | - store / / used to organize the application of Vuex state management. | -. Format of editorconfig / / development tool configuration. | - eslintrc. Js / / ESLint configuration file, Used to check the code format. | - gitignore / / configure git do not upload file | -- nuxt. Config. The json / / used to organize nuxt. Js application personalized configuration, Has override the default configuration | - package - lock. Json / / NPM automatically generated, used to help uniformity of package setting, yarn has the same action | -- package - lock. Json / / NPM automatically generated, To help uniformity of package setting, yarn has the same action | -- package. Json / / NPM package management configuration fileCopy the code

Introduction to main documents:

This part of the content I explained in the video, not too many notes, small friends can watch the video to learn.

Section 03: Common configuration items for Nuxt

Now that we know the Nuxt directory structure, we can actually play with it, but we still feel a lot of constraints, such as IP address and port (localhost:3000) and common CSS. In this lesson, we will learn some common configuration of Nuxt, so that we can develop more freely.

Configure the IP address and port:

It is common for a port to be occupied or an IP address to be specified during development. We need to configure the config item in package.json in the root directory. Let’s say we want to set the IP to 127.0.0.1 and the port to 1818.

/package.json

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

Once configured, we type NPM run dev in the terminal and you will see the service address changed to 127.0.0.1:1818.

Configuring the Global CSS

When developing multi-page projects, we will define a global CSS to initialize our page rendering. For example, we will set the padding and margin to 0. There is also a very famous open source CSS file normailze. To define these configurations, you need to do it in nuxt.config.js.

For example, if you want to set the font to red, go to assets/ CSS /normailze. CSS and set the font to red.

/assets/css/normailze.css

html{
    color:red;
}Copy the code

/nuxt.config.js

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

After setting, enter NPM run dev on the terminal. Then you’ll notice that the font has turned red.

Configure the WebPack loader

It is possible to override the basic configuration of WebPack in nuxt.config.js, for example, we will now configure a URl-loader to pack small images in 64 bits. This can be configured in the build option of nuxt.config.js.

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

If you do not understand this part, you do not know webpack very well, you need to learn the course of Webpack, technology fat has a very good webpack tutorial, I hope to help you “Webpack 3. X version of the Road to God” a total of 26 sets.

Summary: This lesson is mainly about the most commonly used nuxt.js configuration in daily development. The difficulty may be that you have to master webpack, hope friends can start to do these configurations, if you have any questions, you can leave a message to the technical chui in the comment area of the article.

 

Section 04: Nuxt routing configuration and parameter passing

Learning the routing mechanism is essential to learning the front-end framework, because routing can embody our business logic, connect the modules together, and make the application shine. That simply says the route is our jump mechanism, can also be simply understood as link jump. Nuxt.js routing is not complicated, it encapsulates us and saves us a lot of configuration.

Simple Route Demo

We will now create two new folders under the Pages file in the root directory, About and News (imitate the function modules about us and news, see the video if not clear here).

Create a new index.vue file under the About folder and write the following code:

<template>
  <div>
      <h2>About Index page</h2>
      <ul>
        <li><a href="/">Home</a></li>
      </ul>
  </div>
</template>Copy the code

Create a new index.vue file in the news folder and write the following code:

<template>
  <div>
      <h2>News Index page</h2>
       <ul>
        <li><a href="/">Home</a></li>
      </ul>
  </div>
</template>Copy the code

Modify the index.vue folder in the original Pages folder, delete the useless code, and write the following link code:

<template>
  <div>
    <ul>
      <li><a href="/">HOME</a></li>
      <li><a href="/about">ABOUT</a></li>
      <li><a href="/news">NEWS</a></li>
    </ul>
  </div>
</template>
 
<script>
 
export default {
  components: {
   
  }
}
</script>
 
<style>
 
</style>Copy the code

After this little example, you’ll see that it’s all too easy, because nuxt.js does it all for us, without writing any configuration code.

< nuxt – link > tag

Although the jump above was successful, nuxt.js does not recommend this <a> tag. Instead, it provides the <nuxt-link> tag (called component in VUE). Let’s start by replacing the <a> tag on the home page with <nuxt-link>.

<template>
  <div>
    <ul>
      <li><nuxt-link :to="{name:'index'}">HOME</nuxt-link></li>
      <li><nuxt-link :to="{name:'about'}">ABOUT</nuxt-link></li>
      <li><nuxt-link :to="{name:'news'}">NEWS</nuxt-link></li>
    </ul>
  </div>
</template>
 
<script>
 
export default {
  components: {
   
  }
}
</script>
 
<style>
 
</style>Copy the code

We preview the page again, also can be a normal jump, in the actual development as far as possible to use < NUxT-link > tag method jump route.

Params passes parameters

Routing often needs to pass parameters, we can simply use Params to pass parameters, we now pass a parameter to the news page, and then simply receive on the news page.

We first modify the index. vue file under Pages, add params parameter to the news jump, pass 3306ID.

<template>
  <div>
    <ul>
      <li><nuxt-link :to="{name:'index'}">HOME</nuxt-link></li>
      <li><nuxt-link :to="{name:'about'}">ABOUT</nuxt-link></li>
      <li><nuxt-link :to="{name:'news',params:{newsId:3306}}">NEWS</nuxt-link></li>
    </ul>
  </div>
</template>
 
<script>
 
export default {
  components: {
   
  }
}
</script>
 
<style>
 
</style>Copy the code

$route.params.newsId = $route.params.newsId = $route.params.newsId = $route.params.newsId = $route.

<template>
  <div>
      <h2>News Index page</h2>
      <p>NewsID:{{$route.params.newsId}}</p>
       <ul>
        <li><a href="/">Home</a></li>
      </ul>
  </div>
</template>Copy the code

Summary: This section is a brief introduction to routing. If you have a good knowledge of Vue before, you can already make some pleasing small Demo after learning this section. Let’s use our imagination and make a small Demo to practice.

Section 05: Nuxt dynamic routing and parameter verification

Now that we know about simple routing, let’s look at dynamic routing, which is actually routing with parameters. For example, we now have a lot of news details under the news module, at this time we need the help of dynamic routing.

News details page:

$route.params.id = $route.params.id = $route.params.id = $route.

/pages/news/_id.vue

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

Modify the route of the news home page

We modified /pages/news/index.vue to add two detail pages of route news-1 and news-2.

<template>
  <div>
      <h2>News Index page</h2>
      <p>NewsID:{{$route.params.newsId}}</p>
       <ul>
        <li><a href="/">Home</a></li>
        <li><a href="/news/123">News-1</a></li>
        <li><a href="/news/456">News-2</a></li>
      </ul>
  </div>
</template>Copy the code

After the code is written, open NPM run Dev to check, we have entered the news detail page, and obtained the news ID passed in the detail page.

Dynamic parameter check

Nuxt.js also provides the validate() method for verifying the correctness of the passed parameters.

/pages/news/_id.vue

export default {
 
  validate ({ params }) {
    // Must be a number
    return /^\d+$/.test(params.id)
  }
 
}Copy the code

We use the validate method, pass params in, and check with the re. If the re returns true, the page is displayed, and if the re returns false, the page is displayed.

Summary: This lesson mainly explains the dynamic routing of Nuxt, said the writing method of dynamic routing and verification parameter function, hope friends can practice. Practice is the only way to discover problems and learn. Tech fat really hope you can learn this skill.

Section 06: Nuxt routing animations

Route animation effect, also known as page replacement effect. Nuxt.js provides two ways to animate routes, either globally or for individual pages.

Global routing animation

Global animation is set up using page by default, for example now we have a fade in and out effect for each page. We can create a main. CSS file in assets/ CSS in the root directory.

/assets/ CSS /main.css

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

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 switch when switching pages, but you may find some pages are not working because you don’t have the <nuxt-link> component to make the jump link. You need to make changes.

Like the dynamic routing news page we did last time, you need to change the link below.

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

After modification, you will see the animation effect.

Set page dynamic effects separately

To give a page a unique effect, simply change the default page in the CSS and add the Transition field to the configuration of the page component. For example, we want to add a font zoom in and out of the About page that doesn’t exist on other pages.

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

Then set it in the About /index.vue component

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

At this point, there is a unique dynamic effect of the page switch.

Section 07: Default templates and default layouts for Nuxt

When developing applications, common elements are often used, such as the title of a web page being the same, with each page having the same title. We have 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 methods have advantages and disadvantages. For example, common components are more flexible, but you need to import them manually each time. Templates are convenient, but can only be introduced on every page. In this tutorial we will learn how to use Nuxt’s default templates and layout functions.

The default template

Nuxt provides a super easy way to customize the default template by creating app.html in the root directory. Now we want the words “JSPang.com’s tech-fat blog” at the top of every page, so we can use the default template to do this.

<! DOCTYPE HTML > < HTML lang="en"> <head> {{head}} </head> <body> <p>jspang.comCopy the code

{{HEAD}} reads the nuxt.config.js file. {{APP}} is the main page in the pages folder. Note that both HEAD and APP need to be capitalized, and lower case will cause an error.

There’s a little bit of a catch here. If you set up the default template, remember to restart the server, otherwise your display won’t work. But the default layout does not require a server restart.

The default layout

Similar to the default template, there is the default layout, but as you can tell from the name, the default layout is used for unified layout of the page. Its layouts/default.vue in the root directory of the location. Note that there is no header information in the default layout, just customizable content under the

Again, let’s put the words “tech-fat blog of JSPang.com” at the top of each page and see how it works in the default layout.

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

The <nuxt/> here is equivalent to the content of each of our pages. You can also put some generic styles into the default layout, but personally I don’t recommend this as it adds complexity to the page.

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

Section 08: Nuxt error pages and personality meta Settings

A 404 page is essential in application development because we need to give the user a clear guide when they enter a wrong route. Nuxt.js supports creating error pages directly in the default layout folder.

Create an error page

Create an error.vue file in the root layouts folder, which is a component that displays application errors.

<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

The code uses v-if to determine the type of error. Note that this error is declared in <script>, and the program will not find error.statuscode without declaring it.

Here I also use a simple <nuxt-link> to just follow the path.

Personality Meta Settings

Page Meta is very important for SEO Settings. For example, if you want to make a news page, each page needs to have different title and Meta Settings for the news in order to be included in the search engine. Use the head method directly to set the header information for the current page. We will now set the new-1 page to the meta and title of the individual.

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

/pages/news/index.vue

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

2. After the first step, we modified /pages/news/_id. Vue to change it into unique meta and title tags based on the passed values.

<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,}}, head(){return{title:this. meta:[ {hid:'description',name:'news',content:'This is news page'} ] } } } </script>Copy the code

Note: It is recommended that the HID key be used to assign a unique identifier to the meta tag in the child component to avoid duplication of the meta tag in the parent component.

Section 09: asyncData method gets data

In a project, you need to get data before initializing the page, which is often referred to as asynchronous request data. Nuxt.js has nicely extended the vue.js approach for us, adding anyncData. It makes sense from the name that this is a one-step approach.

Creating remote data

To make some fake remote data here, the site I chose was 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 typed at will.

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

After you enter this, the site will give you an address, which is the address of your JSON repository.

https://api.myjson.com/bins/8gdmr

Install Axios

Vue. Js officially recommends using Axios for remote data retrieval, so we install the official recommendation to use Axios. Here we use NPM to install AXIOS. Enter the following command directly in the terminal:

npm install axios --save

Promise method for ansycData

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

< the template > < div > < h1 > name: {{info. Name}} < / h1 > < h2 > age: {{info. Age}} < / h2 > < h2 > interest: {{info.interest}}</h2> </div> </template> <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

At this point we can see that the output is ready in the browser.

Await method of ansycData

Of course, the above method is a little outdated, now all use ansyc… Await to solve asynchrony, rewrite above code.

< the template > < div > < h1 > name: {{info. Name}} < / h1 > < h2 > age: {{info. Age}} < / h2 > < h2 > interest: {{info.interest}}</h2> </div> </template> <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

Section 10: Static resources and packaging

I have been on a business trip for a week, and I am back at last. I can continue to record lessons for my friends. Some of my friends left me comments saying that some images are available during project development, but not after packaging. This lesson will talk about how to place static resources and packaging in nuxt.js project.

Let’s go straight to the image

Download any image from the web, place it under the static folder in your project, and reference it using the import method below

<div><img src="~static/logo.png" /></div>Copy the code

This reference method does not need to estimate the relative path, “~” is equivalent to locating the project and directory, at this time your image path will not be wrong, even if the packaging is normal.

CSS introduces images

If you want to import images in CSS, you do it the same way you would in HTML, using the ~ symbol.

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

This is perfectly normal under NPM run dev, so let’s take a look at packaging.

Package the static HTML and run it

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

npm run generate
 Copy the code

A dist folder is generated, which contains the production static HTML file, and it is placed directly on the server to run.

If you don’t know Node or any other server, you can simply install the simplest server -live-server.

npm install -g live-server
 Copy the code

Then type live-server in the dist folder.

Conclusion: 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. I believe that after 10 lessons, you can already make the effect you want, and the skill tree of Nuxt.js is also lit up. I’m looking forward to more practical lessons. I’ll see you next time.