Server-side rendering-Nuxt.js basics

Preface

An article on the server side rendering basis , introduced the advantages and disadvantages of various rendering modes, and in the end use vue.jsof Nuxt.jsby a small case, the experience of modern server rendering mode.


Nuxt.js definition

  • Nuxt.jsIs based on a Vue.jsserver-side rendering application framework, through the abstract organization of client / server infrastructure, Nuxt.jsthe main concern is the UI rendering application, you can easily achieve homogeneous application
  • As a client/server framework, it provides many useful features:
    • based on Vue.js
    • Automatic code layering
    • Server-side rendering
    • Powerful routing function, support asynchronous data
    • Static file service
    • ES2015+ Grammar support
    • Packing and compression JSandCSS
    • HTML head tag management
    • Local development supports hot reloading
    • integrated ESLint
    • Pre-processor supports a variety of SASSstyles: LESS, , Stylusetc.
    • Support HTTP/2Push

Nuxt.js use scope

Nuxt.jsMainly used in the following situations:

  1. Use to Nuxt.jsinitialize a brand new project
  2. For existing node.jsserver project, directly Nuxtas a middleware integration into Node Web Serverthe
  3. Solve the disadvantages of Vue.jsslow loading of the first screen of existing projects and unfavorable SEOdefects. In this case, developers are required Nuxtto have a high degree of mastery, and the amount of code changes is large, at least 10% changes.

Create Nuxt project

Nuxt.js There are two ways to create a project:

Create a project manually, enter the project directory

# 初始化 package.json 文件
yarn init
# 安装 nuxt
yarn add nuxt

Added in the package.jsondocument scripts:

"scripts": {
    
    
   "dev": "nuxt" //可以通过运行npm run dev来运行nuxt
},

Create a new pagesdirectory, create the first pagepages/index.vue

<template>
  <div>
    <h1>Hello Nuxt.js</h1>
  </div>
</template>

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

<style>

</style>

Startup project

yarn dev

The application http://localhost:3000is running on, check whether it can be accessed on the browser.

Note: Nuxt.js will monitor file changes in the pages directory, so there is no need to restart the application when adding new pages.

routing

Ordinary routing

The Vue.jsdifference is that there is Nuxt.jsno need for the developer to explicitly define vue-routerrouting rules in the project. The routing configuration of the module Nuxt.jswill be automatically generated based pageson all the *.vuefiles in the directory vue-router, find the folder index.vueand use it as the component of the root path of this folder .

pagesThe directory structure is as follows:

pages/
--| user/
-----| index.vue
-----| info.vue
--| index.vue

Nuxt.js The automatically generated routing configuration is as follows:

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

Route navigation

Nuxt.jsProviding routing component nuxt-linkfor a jump between pages, and its role router-link same through the totarget address attribute, a default tag rendered with the correct links can be configured tagto generate another tag attributes.

<nuxt-link to="/">跳转到首页</nuxt-link>

Also supports navigation routing program, and method of use Vue.jsof the program navigation consistent

<button @click="onClick">跳转到首页</button>

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

It also supports the use of <a></a>tags for page jumps, but this method will refresh the page and send a request to the server, so it is not recommended.

Nested routing

Nuxt.jsProvides three ways to implement nested routing.

  • By vue-routersub-routes create Nuxt.jsa nested routing applications
  • In nuxt.config.jsby extendRoutescustom routing rules
  • Use Nuxt.jsaccording to pagesall directory *.vueautomatically generated file vue-routerrouting module configuration rules, but the following two conditions need to be met:
    • Add a .vuefile, while adding a directory with the same file name to store it in the sub-assembly view
    • Within parent components ( .vuein the paper) to increase the content of a display sub-view (corresponding to vue.jsa router-view)

As shown in the figure below, the parent component students.vue, its child components are stored in the studentsdirectory with the same name

Insert picture description here

Dynamic routing

By extendRoutescustom set of routing rules, the dynamic routing rules vue matching with dynamic routing matching , in Nuxt.jsdynamic routing which defines parameters need to create corresponding to underscore prefixed Vuefiles or directories.

The directory structure is as follows:

pages/
--| _slug/
-----| comments.vue
-----| index.vue
--| users/
-----| _id.vue
--| index.vue

Nuxt.js The corresponding routing configuration table is generated as follows:

router: {
    
    
  routes: [
    {
    
    
      name: 'index',
      path: '/',
      component: 'pages/index.vue'
    },
    {
    
    
      name: 'users-id',
      path: '/users/:id?',
      component: 'pages/users/_id.vue'
    },
    {
    
    
      name: 'slug',
      path: '/:slug',
      component: 'pages/_slug/index.vue'
    },
    {
    
    
      name: 'slug-comments',
      path: '/:slug/comments',
      component: 'pages/_slug/comments.vue'
    }
  ]
}

Custom routing configuration

base is used to nuxt.config.jsconfigure the root path of the application, for example:

//nuxt.config.js

module.exports = {
    
    
  router: {
    
    
     base: '/app'  //默认路由改为http://localhost:3000/app/
  }
}

extendRoutes extends the routes created by Nuxt.js or custom routing configuration rules. The following example configures custom routing table rules

//nuxt.config.js

module.exports = {
    
    
  router: {
    
    
    extendRoutes(routes, resolve) {
    
    
      routes.splice(0);//清除nuxtjs根据Pages目录生成的默认路由
      routes.push(...[
        {
    
    
          path: '/',
          component: resolve(__dirname, 'pages/layout/'),
          children: [
            {
    
    
              path: '', //默认子路由
              name: 'home',
              component: resolve(__dirname, 'pages/home/')
            },
            {
    
    
              path: '/login',
              name: 'login',
              component: resolve(__dirname, 'pages/login/')
            }
          ]
        }
      ]); 
    }
  }
}

view

Nuxt.jsThe components of the view are shown in the following figure:

Insert picture description here

template

Nuxt.jsThe default template is:

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

In the srcfolder (default is the application root directory) to create a app.htmlfile you can customize the default html template.

layout

According to Nuxt.jsthe catalog rules, if there are no additional configuration items in an application, the layout components must be written in the layout catalog layouts.

  • Default layout

By layouts/default.vueextend the default layout of the application file, the file must be added <nuxt/>component for displaying the main content of the page.

<template>
  <div>
    <ul>
      <li>
        <!--相当于router-link-->
        <nuxt-link to="/">首页</nuxt-link>
      </li>
      <li>
        <nuxt-link to="/about">关于</nuxt-link>
      </li>
    </ul>
    <!--页面路由视图,相当于router-view-->
    <nuxt></nuxt>
  </div>
</template>
  • Custom layout

layouts Each file (top level) in the directory will create a custom layout that can be accessed through the layout property in the page component.

For example to create a blog layout layouts/blog.vue:

<template>
  <div>
    <div>我的博客导航栏在这里</div>
    <nuxt />
  </div>
</template>

Then you must layoutspecify the custom layout referenced by this page in the corresponding page :

<template>
   ···
</template>
<script>
  export default {
    
    
    layout: 'blog'
  }
</script>
  • Error page

Nuxt.jsThe provisions of layoutsall the files in the root directory of all belong to personalized layout files, in addition to layouts/error.vue(not need to include <nuxt/>the label), this file in the layoutsfolder, but it is a page for custom error pages (pages 404, 500).

For example, a customized 404page:

template>
  <div class="container">
    <h1 v-if="error.statusCode === 404">页面不存在</h1>
    <h1 v-else>应用发生错误异常</h1>
    <nuxt-link to="/">首 页</nuxt-link>
  </div>
</template>

<script>
  export default {
    
    
    props: ['error'],
    layout: 'blog' // 为错误页面指定自定义的布局
  }
</script>

page

Nuxt.jsThe page of is actually Vuecomponents, and some special configuration items are added on the basis of these components .

<template>
  <div>
    <h1>{
    
    {
    
     title1 }}</h1>
    <ul>
      <li v-for="item in list" :key="item.id">
        {
    
    {
    
     item.title }}: {
    
    {
    
     item.content }}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
    
    
  name: "Home",
  //Nuxt.js中的钩子函数,专门用于获取页面服务端渲染的数据
  async asyncData() {
    
    
    ...
  }
};
</script>

data

Nuxt.jsAn asyncData method has been added, which can obtain or process data asynchronously before setting the data of the component.

It can only be used in page components, and cannot be used in the
asyncData method of subcomponents of page components . This cannot be used because it is called before the page component is initialized

When to call:

  • asyncDataMethod will be called before the page component is loaded
  • Called during server rendering and before client routing updatesasyncData

Parameters and return value:

  • asyncDataThe first parameter is set to the context object of the current page (including request / response / params / query / store)
  • Nuxt.jsThe asyncDatareturned data and the component datamethod return data will be fused together for use by the component

Nuxt.js Several different methods are provided to use the asyncData method:

  • Use async,await
<template>
  ...
</template>

<script>
export default {
    
    
  async asyncData({
    
     params }) {
    
    
    const {
    
     data } = await axios.get(`https://my-api/posts/${
    
    params.id}`)
    return {
    
     title: data.title }
  }
}
</script>
  • Return one Promise, it nuxt.jswill wait for it to Promisebe parsed before setting the data of the component to render the component
<template>
  ...
</template>

<script>
export default {
    
    
  asyncData({
    
     params }) {
    
    
    return axios.get(`https://my-api/posts/${
    
    params.id}`).then(res => {
    
    
      return {
    
     title: res.data.title }
    })
  }
}
</script>

Article list

Server-side rendering basic
server-side rendering-Nuxt.js basic
server-side rendering-Nuxt.js comprehensive case
server-side rendering-Nuxt.js comprehensive case release deployment
server-side rendering-Vue SSR construction

Guess you like

Origin blog.csdn.net/weixin_41269811/article/details/112341863