Big front-end learning - NuxtJS study notes

NuxtJS study notes

Article content output source: big front-end high-paying training camp

Code warehouse address: https://gitee.com/jiailing/nuxtjs-demo , there are codes in multiple branches

1. What is Nuxt.js

  • A third-party open source server-side rendering application framework based on the Vue.js ecosystem
  • It can help us easily use the Vue.js technology stack to build isomorphic applications
  • Official website: https://zh.nuxtjs.org/
  • Github repository: https://github.com/nuxt/nuxt.js

2. How to use Nuxt.js

  • Initialize the project
  • Existing Node.js server project
    • Directly integrate Nuxt as a middleware into Node Web Server
  • Existing Vue.js project
    • Very familiar with Nuxt.js
    • At least 10% code changes

Three, initialize Nuxt.js application method

Official document: https://zh.nuxtjs.org/guide/installation

  • Method 1: Use create-nuxt-app
  • Method 2: Manually create

Four, Nuxt.js routing

1. Basic routing

The files in the pages folder will automatically generate routes

2. Route navigation

  • a tag

    • It will refresh the entire page and is not recommended
    • <a href="/">首页</a>
  • nuxt-link component

    • https://router.vuejs.org/zh/api/#router-link-props
    • <router-link to="/">首页</router-link>
  • Programmatic navigation

    • https://router.vuejs.org/zh/guide/essentials/navigation.html

    • <button @click="onClick">首页</button>

      methods: {
              
              
        onClick () {
              
              
          this.$router.push('/')
        }
      }
      

3. Dynamic routing

user/_id.vue, the dynamic routing parameter file name starts with an underscore.

<template>
  <div>
    <h1>User page</h1>
    <p>{
   
   {$route.params.id}}</p>
  </div>
</template>

<script>
export default {
     
     
  name: 'UserPage'
}
</script>

<style scoped>

</style>

4. Nested routing

You can create nested routes for Nuxt.js applications through sub-routes of vue-router. To create an embedded sub-route, you need to add a Vue file and a directory with the same name as the file to store the sub-view components.

Warning: Do not forget within parent components ( .vuein the paper) to increase <nuxt-child/>a display sub-view content.
Insert picture description here

4. Routing configuration

  • Reference document: https://zh.nuxtjs.org/api/configuration-router

  • Create nuxt.config.js in the project root directory

    /**
     * Nuxt.js 配置文件 nuxt.config.js
     */
    
     module.exports = {
          
          
       router: {
          
          
         base: '/abc',
         // routes就是路由配置表,是个数组,resolve是解析路由路径的
         extendRoutes(routes, resolve) {
          
          
          routes.push({
          
          
            name: 'custom',
            path: '*',
            component: resolve(__dirname, 'pages/404.vue')
          }),
          routes.push({
          
          
            name: 'hello',
            path: '/hello',
            component: resolve(__dirname, 'pages/about.vue')
          })
        }
       }
     }
    

Five, Nuxt.js view

Insert picture description here

1. Template

You can customize the default application template of Nuxt.js.

Customized default html template, just under the src folder (default is the application root directory) to create a app.htmlfile.

The default template is:

<!DOCTYPE html>
<html {
     
     {
     
      HTML_ATTRS }}>
  <head {
     
     {
     
      HEAD_ATTRS }}>
    {
   
   { HEAD }}
  </head>
  <body {
     
     {
     
      BODY_ATTRS }}>
    {
   
   { APP }}
  </body>
</html>

Insert picture description here

2. Structure

Nuxt.js allows you to extend the default layout, or layoutcreate a custom layout directory.

It can be added layouts/default.vueto extend the application of the default layout file.

Tip: Do not forget to add in the layout file <nuxt/>component is used to display the main content of the page.

The source code of the default layout is as follows:

<template>
  <nuxt />
</template>

Insert picture description here

You can modify the default layout component through the layout attribute in the component:

Insert picture description here

The layout component of the Index page becomes foo, but the about page is still default, because the about page has not modified its layout attribute, so the default layout file is still default

Six, Nuxt.js asynchronous data

1. asyncData method

Nuxt.js extends Vue.js and adds a asyncData method called , which allows us to obtain or process data asynchronously before setting the data of the component.

  • https://zh.nuxtjs.org/guide/async-data
  • Basic usage
    • It will merge the data returned by the asyncData component data method to return the data to the component
    • Call timing: during server-side rendering and before client-side routing updates (ensure that both the server and the client are running to process data)
  • Precautions
    • It can only be used in page components. The asyncData method will not be called in non-page components. If data is needed in the sub-components, the data can be passed through props
    • There is no this because it is called before the component is initialized

When the dynamic page content you want to use is conducive to SEO or to improve the rendering speed of the first screen, send the request data in asyncData. If it is non-asynchronous data or ordinary data, it can be initialized to data normally.

Pages / index.vue

<template>
  <div>
    <h1>Hello {
   
   { title }}!</h1>
    <Foo />
    <nuxt-link to="/about">about</nuxt-link>
  </div>
</template>

<script>
import axios from 'axios'
import Foo from '@/components/Foo'

export default {
     
     
  name: 'HomePage',
  components: {
     
     
    Foo
  },
  async asyncData () {
     
     
    // 如果验证asyncData是在服务端执行的?可以通过log输出在了服务端控制台,得出这个方法是在服务端执行的。Nuxtjs为了方便调试,把服务端控制台输出数据也打印在了客户端控制台,但是为了区分,在客户端控制台用“Nuxt SSR”包裹起来了
    console.log('asyncData')
    const res = await axios({
     
     
      method: 'GET',
      url: 'http://localhost:3000/data.json'// 这里的请求地址要写完整,因为在服务端渲染期间,也要来请求数据,不写完整的话服务端渲染就会走到80端口,如果只是客户端渲染,就会以3000端口为基准来请求根目录下的data.json,服务端渲染就默认走到80了
    })
    // 返回的数据会与data中的数据混合
    return res.data
  },
  data () {
     
     
    return {
     
     
      foo: 'bar'
    }
  }
}
</script>

<style scoped>

</style>

pages/components/Foo.vue

<template>
  <div>
    <h1>Foo</h1>
    此处会报错,因为这是非页面组件,asyncData方法不会执行,所以foo是未定义。
    <h3>{
   
   {foo}}</h3>
  </div>
</template>

<script>
export default {
     
     
  name: 'FooPage',
  asyncData () {
     
     
    return {
     
     
      foo: 'bar'
    }
  }
}
</script>

<style scoped>

</style>

The static folder can be accessed directly as the root path

2. Context Object

pages / article / _id.vue

<template>
  <div>
    <h1>article Page </h1>
    <nuxt-link to="/">首页</nuxt-link>
    <h3>title: {
   
   {post.title}}</h3>
  </div>
</template>

<script>
import axios from 'axios'

export default {
     
     
  name: 'ArticlePage',
  async asyncData (context) {
     
     
    // asyncData的参数为上下文对象,我们无法在这个方法里使用this,所以无法通过this.$router.params.id拿到路由参数,但是可以通过context.params.id获取参数
    console.log(context) 
    const {
     
      data: {
     
     posts} } = await axios({
     
     
      method: 'GET',
      url: 'http://localhost:3000/data.json'
    })
    const id = parseInt(context.params.id, 10)
    return {
     
     
      post: posts.find(item => item.id === id),
    }
  }
}
</script>

Components/Foo.vue

<template>
  <div>
    <h1>Foo</h1>
    <ul>
      <li v-for="item in posts" :key="item.id">
        <nuxt-link :to="'/article/'+item.id">{
   
   {item.title}}</nuxt-link>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
     
     
  name: 'FooPage',
  props: ["posts"]
}
</script>

<style scoped>

</style>

pages / index.vue

<template>
  <div>
    <h1>Hello {
   
   { title }}!</h1>
    <Foo :posts="posts" />
    <nuxt-link to="/about">about</nuxt-link>
  </div>
</template>

<script>
import axios from 'axios'
import Foo from '@/components/Foo'

export default {
     
     
  name: 'HomePage',
  components: {
     
     
    Foo
  },
  async asyncData () {
     
     
    // 如果验证asyncData是在服务端执行的?可以通过log输出在了服务端控制台,得出这个方法是在服务端执行的。Nuxtjs为了方便调试,把服务端控制台输出数据也打印在了客户端控制台,但是为了区分,在客户端控制台用“Nuxt SSR”包裹起来了
    console.log('asyncData')
    const res = await axios({
     
     
      method: 'GET',
      url: 'http://localhost:3000/data.json'// 这里的请求地址要写完整,因为在服务端渲染期间,也要来请求数据,不写完整的话服务端渲染就会走到80端口,如果只是客户端渲染,就会以3000端口为基准来请求根目录下的data.json,服务端渲染就默认走到80了
    })
    // 返回的数据会与data中的数据混合
    return res.data
  },
  data () {
     
     
    return {
     
     
      foo: 'bar'
    }
  }
}
</script>

<style scoped>

</style>

Guess you like

Origin blog.csdn.net/jal517486222/article/details/107810075