[Vue] vue server-side rendering nuxt.js

initialization

The use of scaffolding create-nuxt-app tools to quickly create

npx create-nuxt-app <项目名>

npx create-nuxt-app <project name>

Perform some selection

  1. Selecting between the integrated server framework:
  2. Select your favorite UI framework:
  3. Select your favorite testing framework:
  4. Select what you want Nuxt mode (Universal or SPA)
  5. Add axios module to easily sends an HTTP request to your application.
  6. Add EsLint to code specifications and error checking when you save your code.
  7. Add Prettier to format when saving / beautify your code.

Nuxt.js Features

  • Based Vue.js
  • Automatic code stratified
  • Side rendering service
  • Powerful routing capabilities to support asynchronous data
  • Static files
  • ES6 / ES7 syntax support
  • Package and compress JS and CSS
  • HTML head tag management
  • Local development support hot load
  • Integrated ESLint
  • Pre-processor supports a variety of styles: SASS, LESS, Stylus etc.

The basic configuration nuxt

Modify pages / index.vue

 <h1 class="title">Hello world</h1>

In localhost: 3000 you can see the updated results

Nuxt directory structure

|-- .nuxt                            // Nuxt自动生成,临时的用于编辑的文件,build
|-- assets                           // 用于组织未编译的静态资源入LESS、SASS 或 JavaScript
|-- components                       // 用于自己编写的Vue组件,比如滚动组件,日历组件,分页组件
|-- layouts                          // 布局目录,用于组织应用的布局组件,不可更改。
|-- middleware                       // 用于存放中间件
|-- pages                            // 用于存放写的页面,我们主要的工作区域
|-- plugins                          // 用于存放JavaScript插件的地方
|-- static                           // 用于存放静态资源文件,比如图片
|-- store                            // 用于组织应用的Vuex 状态管理。
|-- .editorconfig                    // 开发工具格式配置
|-- .eslintrc.js                     // ESLint的配置文件,用于检查代码格式
|-- .gitignore                       // 配置git不上传的文件
|-- nuxt.config.json                 // 用于组织Nuxt.js应用的个性化配置,已覆盖默认配置
|-- package-lock.json                // npm自动生成,用于帮助package的统一性设置的,yarn也有相同的操作
|-- package-lock.json                // npm自动生成,用于帮助package的统一性设置的,yarn也有相同的操作
|-- package.json                     // npm包管理配置文件
Aliases table of Contents
~ Or @ SRCDIR
Or @@ ~~ rootDir

Vue in your template, if you need to introduce assets or static directory, use ~ / assets / your_image.png and ~ / static / your_image.png way.

Configuring IP and port

Configure the config entry in the root directory package.json

  "config":{
    "nuxt":{
      "host":"127.0.0.1",
      "port":"1818"
    }
  },

Configuring Global css

To define a global CSS to initialize our page rendering, where the use normailze.css.

New assets / css / normalize.css

Modify nuxt.config.js

css: ["element-ui/lib/theme-chalk/index.css", "~assets/css/normailze.css"],

normalize.css

Modify the configuration webpack

Webpack may be arranged in the cover of the 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)/
        })
      }
    }
  }

Write a demo

Write a test demo (to find a site copy copy), take a look at the basic process

npm install iview --save
或
vue add iview (需要vue-cli支持)

Introduction and configure iview

Wants to join other configurations, may be added in nuxt.config.js plugins configuration item, while introducing logic plugins folder added. E.g:

nuxt.config.js

{src: '~plugins/iview', ssr: true}

At the same time new plugins / iview.js

import Vue from 'vue'
import iView from 'iview'

Vue.use(iView)
import 'iview/dist/styles/iview.css'

Modifying the Default Layout

May default layout by adding layouts / default.vue files to extend the application

<template>
    <div class="layout">
  ......
    </div>
</template>

The traditional use of the spa But in the nuxtjs .Created component displays the main content and data in the logical page is in the process of loading the server, not the browser, such as logic browser window such as location or object you want to write mounted, otherwise it will error .head define some of the metadata, the metadata will be crawling reptiles that can customize each page.

Adding static resource

Online casually next picture, and then create pages / index

<template>
    <div class="container">
        <div>
            <Card v-for="i in 5" :key="i" :style="{width:'100%',marginBottom:'15px'}">
                <div style="text-align:center">
                    <img src="~/static/image/cat.jpg" height="300px" />
                    <h3>A high quality UI Toolkit based on Vue.js</h3>
                </div>
            </Card>
        </div>
    </div>
</template>

@ ~ And it can be used to introduce picture

Routing nuxt use

The base is nuxt routing according to the directory structure for example pages to generate pages / index.vue is {name: 'index', path: '/', component: 'pages / index.vue'}, empathy pages / books / index.vue is {name: 'books', path: '/ books', component: 'pages / books / index.vue'}

Modify the layout / default.vue

<Menu mode="horizontal" theme="dark" active-name="1">
  <div class="layout-logo"></div>
  <div class="layout-nav">
    <MenuItem name="1">
      <Icon type="ios-navigate"></Icon>
      <nuxt-link to="/">首页</nuxt-link>
    </MenuItem>
    <MenuItem name="2">
      <Icon type="ios-keypad"></Icon>发现
    </MenuItem>
    <MenuItem name="3">
      <nuxt-link to="/books">小书</nuxt-link>
    </MenuItem>
  </div>
</Menu>

Nuxt.js Recommended Tag to build the routing system

asyncData method to get the data

Use asyncData method allows us to acquire or process data asynchronously setting data before assembly. asyncData method goes to components (limited to the page assembly) is called before every load. It may be called before the server or routing updates. When this method is called, the first parameter is set to the current page context object, you can use asyncData method to get the data, Nuxt.js will asyncData returned data component data fusion method returns data together return to the current component. Since asyncData initialization method is invoked before assembly, so the method is in no way to refer to an object instance of the component by this.

npm install axios --save

Create a fake dummy data on http://myjson.com/

{
  "data": [
    {
      "name": "Cesium基础功能-鹰眼地图。附带源码下载"
    },
    {
      "name": "iOS开发简记(7):网络请求模块"
    },
    {
      "name": "iOS开发简记(7):网络请求模块"
    },
    {
      "name": "(难度Hard) Problem 132. Palindrome Partitioning II(回文串拆分II)"
    },
    {
      "name": "iOS 13适配问题"
    },
    {
      "name": "Cesium基础功能-气泡弹窗。附带源码下载"
    },
    {
      "name": "重学安卓:是让人耳目一新的 Jetpack MVVM 精讲啊!"
    },
    {
      "name": "iOS开发简记(6):storyboard的使用"
    },
    {
      "name": "最熟悉的陌生人:5 分钟快速理解 HTTP2"
    }
  ]
}

Copy and paste, click Save, get the address https://api.myjson.com/bins/f1bdx

New pages / index.vue

<template>
    <div class="container">
        <div>
            <Card v-for="(item,index) in books" :key="index" :style="{width:'100%',marginBottom:'15px'}">
                <div style="text-align:center">
                    <img src="~/static/image/cat.jpg" height="300px" />
                    <h3>{{ item.name }}</h3>
                </div>
            </Card>
        </div>
    </div>
</template>
<script>
import axios from 'axios'
export default {
  async asyncData(){
      let {data}=await axios.get('https://api.myjson.com/bins/f1bdx')
      return {info: data}
  }
}
</script>

Nuxt page meta settings

Special configuration items Nuxt.js to pages provided. Head configuration in which the current page Meta tags, details refer to the page header configuration API .

    head: {
        title: '一本书 - 首页',
        meta: [
            {
                hid: 'description',
                name: 'description',
                content: 'website description'
            },
            { name: 'keywords', content: '一本书,码农,技术,vue,node,nuxt,前端' }
        ]
    },

Open page -> Refresh -> Right view, the effect on the show, which is a big advantage nuxt

Add a Page switching effects

Global animation using the page to the default settings, for example, now we are set to fade when entering and exiting a fade effect for each page. We can first establish a main.css file in assets / css root directory.

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

Then join in a global nuxt.config.js in the css file on it.

css:['assets/css/main.css'],

The current official settings Components making the jump link only animation

Make a details page

Modify pages / books / index.vue

<Row type="flex" gutter="10" justify="start" class="code-row-bg">
  <Col v-for="i in 10" :key="i" span="6">
    <Card style="width:100%">
      <nuxt-link :to="'/books/'+i">
        <div style="text-align:center">
          <img style="width:100%" src="https://img3.doubanio.com/view/subject/m/public/s6974202.jpg" />
          <h3>史蒂夫·乔布斯传</h3>
        </div>
      </nuxt-link>
    </Card>
  </Col>
</Row>

In dynamic routing Nuxt.js which is defined with parameters, you need to create corresponding to underscore Vue file or directory prefix. That is, either create _id.vue, or create _id / index.vue

New pages / books / _id.vue

<template>
    <div>
        <Card style="width:100%">
            <div style="text-align:center">
                <img style="width:100%" src="https://img3.doubanio.com/view/subject/m/public/s6974202.jpg" />
                <h3>史蒂夫·乔布斯传</h3>
                <p>当前id : {{ id }}</p>
            </div>
        </Card>
    </div>
</template>

<script>
export default {
    validate({ params }) {
        return /^[0-9]+$/.test(params.id)
    },
    data() {
        return {
            id: this.$route.params.id
        }
    },
    head() {
        return {
            title: '史蒂夫·乔布斯传',
            meta: [{ hid: 'description', name: 'books', content: '史蒂夫·乔布斯传' }]
        }
    }
}
</script>

Adding the site to the entire head

Nuxt.js application allows you to define all the necessary default meta tags in the head field configuration in nuxt.config.js in on it

New root / app.html

<!DOCTYPE html>
<html lang="en">
    <head>
        {{
            HEAD
        }}
    </head>

    <body>
        {{ APP }}
    </body>
</html>

nuxt in fact some of the requirements have to be developed are ready to use server-side rendering vue nuxt be able to greatly improve development efficiency

The final package

Static application deployment

npm run generate

demo

reference

Guess you like

Origin www.cnblogs.com/mybilibili/p/11591917.html