The originallink

instructions

This article is based on the starter-template template for children with vuE-CLI development experience

vue init nuxt-community/starter-template
Copy the code

Nuxt

The official documentation

Nuxt is simply a VUe-based application framework that uses server-side rendering to give your SPA application (Vue) SEO

The life cycle

As we all know, Vue’s life cycle is all on the client side (browser), while Nuxt’s life cycle is some on the server side (Node), client, or both:


Life cycle flow chart,
The red box shows the Nuxt life cycle (running on the server), the yellow box shows it running on the server && client, and the green box shows it running on the client

Actual combat experience

1. The periods in the red and yellow boxes do not contain Window objects

<script>
export default {
  asyncData() {
    console.log(window) // The server reported an error
  },
  fetch() {
    console.log(window) // The server reported an error
  },
  created () {
    console.log(window) // undefined
  },
  mounted () {
    console.log(window) // Window {ƒ : ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window,... }}}</script>
Copy the code

2. Configure the error page

You can customize the error page by editing the layouts/error.vue file.

<template>
  <div class="container">
    <h1 v-if="error.statusCode === 404">Page does not exist</h1>
    <h1 v-else>Application error exception occurred. Procedure</h1>
    <nuxt-link to="/">The first page</nuxt-link>
  </div>
</template>

<script>
export default {
  props: ['error'].layout: 'blog' // You can specify a custom layout for error pages
}
</script>
Copy the code

3. Customize the Loading page

nuxt.config.js

module.exports = {
  loading: '~components/loading.vue'
}
Copy the code

loading.vue

<template lang="html">
  <div class="loading-page" v-if="loading">
    <p>Loading...</p>
  </div>
</template>

<script>
export default {
  data: (a)= > ({
    loading: false
  }),
  methods: {
    start () {
      this.loading = true
    },
    finish () {
      this.loading = false}}}</script>
Copy the code

4. Verify parameters

If the verification fails, the error page is displayed

<script>
export default {
  validate({ params, query }) {
    return /^d+$/.test(params.id) // must be number}}</script>
Copy the code

5. Where do you put common components like Header and Footer?

As you all know, vue-CLI entry file is app.vue, which in nuxt development is./layout/default.vue

<template>
  <div id="app">
    <! -- Public header component -->
    <xxx-header></xxx-header>
    <! Router view -- router view
    <nuxt/>
    <! -- Common bottom component -->
    <xxx-footer></xxx-footer>
  </div>
</template>
Copy the code

6. Not keep alive

Keep-alive is not supported for server rendering, so the natural activated and deactivated lifecycleare not supported

7. Configure the plug-in

All plug-ins are written in the /plugins directory, using vue-lazyLoad as an example

plugins/lazy-load.js

import Vue from 'vue'
import VueLazyLoad from 'vue-lazyload'

Vue.use(VueLazyLoad, {
  loading: require('~/assets/images/loading.jpg'),
  error: require('~/assets/images/error.jpg')})Copy the code

nuxt.config.js

module.expors = {
  plugins = [
    {
      src: "~/plugins/lazy-load",
      ssr: false}}]Copy the code

8. Use Axios and configure global interceptors to handle cross-domain

The rogers-template template is recommended to use @nuxtjs/axios and @nuxtjs/proxy, which do not need to be configured in plugins

Install dependencies

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

Use and process cross-domains

// nuxt.config.js
module.exports = {
  modules: [ '@nuxtjs/axios'].// No need to add @nuxtjs/proxy
  axios: {
    proxy: true,
    prefix: '/api'.// baseURL
    credentials: true,
  },
  proxy: {
    '/api/': {
      target: 'http://127.0.0.1:2001'.// Proxy address
      changeOrigin: true,
      pathRewrite: {
        '^/api': ' '}},}}Copy the code

Use in components

<script>
export default {
  fetch ({ app }) {
    console.log(app.$axios)
  },
  asyncData ({ app }) {
    console.log(app.$axios)
  },
  created () {
    console.log(this.$axios)
  }
}
</script>
Copy the code

At this point, we don’t need to configure AXIos in plugins, but to set up global interceptors, we need to create a new /plugins/axios.js

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'

  // Request a callback
  axios.onRequest(config= > {})

  // Return the callback
  axios.onResponse(res= > {})

  // Error callback
  axios.onError(error= >{})}Copy the code

Then configure it in plugins

module.exports = {
  plugins = [
    {
      src: "~/plugins/axios",
      ssr: false]}},Copy the code

9. Default Meta tags

nuxt.config.js

module.exports = {
  head: {
    title: 'your project title',
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' }
    ],
    link: [
      { rel: 'stylesheet', href: 'https://fonts.googleapis.com/css?family=Roboto'}}}]Copy the code

10. Meta tags specific to page components

<script>
export default {
  head () {
    return {
      meta: [{name: 'keywords'.content: "Best man, chicken tonight."},]}}}</script>
Copy the code

11. Fill Meta tags of dynamic routes

For example, since the data is asynchronously acquired, we need to write the data acquisition in the asyncData hook, and the page component will be rendered after the data acquisition is successful

<script>
export default {
  async asyncData ({ app, params }) {
    let data = await app.$axios.get(`/appinfo/${params.id}`);
    return {
      appname: data.appinfo.appname
    }
  },
  head () {
    return {
      meta: [{name: 'keywords'.content: `The ${this.appname}, infinite gems, infinite ingot},]}}}</script>
Copy the code

12. Use Vuex

Nuxt has its own vuex integration, so you don’t need to install it, just create index.js in the /store directory

import Vuex from 'vuex'

let store = (a)= > new Vuex.Store({
  state: {
    token: ' '
  },
  mutations: {
    setToken (state, token) {
       state.token = token
    }
  }
})

export default store
Copy the code

13. Login status?

Vuex-persistedstate is used for vuex-CLI projects. It enables persistent vuex state and not lose page refresh. Of course, I prefer vue-cookies to save tokens. The question is, how does nuxt project save login status? A created hook does not contain a Window object. In this case, you must locate a token in mounted to check whether a token exists. This means that the moment the page comes in, you can’t tell if you’re logged in or not, which can result in a slow display of the user name and components hidden

Nuxt is very friendly in that it provides fetch hooks and nuxtServerInit, both of which run on the server side and allow us to manipulate stores very quickly

14. Use of fetch

If a page component sets the fetch method, it will be called before each load of the component (before the server or switch to the destination route), and this method needs to work with someone on the server

<script>
export default {
  async fetch ({ app, store, params }) {
    let { data } = app.$axios.get('/token');
    store.commit('setToken', data.token); }}</script>
Copy the code

15. nuxtServerInit

The ultimate invincible method

import Vuex from 'vuex'

let store = (a)= > new Vuex.Store({
  state: {
    token: ' '
  },
  mutations: {
    setToken (state, token) {
       state.token = token
    }
  },
  actions: {
    nuxtServerInit({ commit }, { req }) {
      let cookie = req.headers.cookie;

      // Convert cookies to JSON objects (implement this method yourself)
      let token = cookieparse(cookie).token;
      commit('setToken', token); }}})export default store
Copy the code

Encapsulate your own global methods

 let xielikang = function () {

  /** * @method Print message method * @param {String} MSG message */
  let message = function (msg) {
    msg && console.log(msg)
  }

  let otherfn = function (msg) {}

  return {
    message,
    otherfn
  }

}

Vue.prototype.$kang= xielikang
Copy the code

Component calls

<script>
export default {
  created() {
    this.$kang.message('What's wrong with you, little man?')}}</script>
Copy the code

Also, don’t forget to configure in plugins, which you can check out in section 7

17. Global styles

nuxt.config.js

module.exports = {
  css: ['~/assets/stylesheets/main.min.css']}Copy the code

18. Use the Element – the UI

Create elder-ui.js again from the plugins folder

// global import
import Vue from 'vue'
import ElementUI from 'element-ui'

Vue.use(ElementUI)

// Import on demand
import { Button, Loading, MessageBox } from 'element-ui'

Vue.use(Button)
Vue.prototype.$loading = Loading.service
Vue.prototype.$msgbox = MessageBox
Copy the code

nuxt.config.js

module.exports = {
  css: ['element-ui/lib/theme-chalk/index.css'],
  plugins: [
    {
      src: "~/plugins/element",
      ssr: true}}]Copy the code

18. How to use the SASS preprocessor

Install dependencies

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

Component (no additional configuration required)

<style lang="scss" scoped>

</style>
Copy the code

19. Scope of fetch, asyncData and validate

Use only on page components, i.e. components in the Pages directory, not components in the Components directory

20. Traditional deployment

npm run build && npm run start
Copy the code

21. The pm2 deployment

It allows you to keep your applications permanently active and reload them without downtime, eliminating the need for the.nuxt folder of traditional deployments, which also include hot updates as in production environments

npm install pm2 -g
Copy the code
npm run build
pm2 start ./node_modules/nuxt/bin/nuxt-startCopy the code





Author: daydreammoon


Link: https://www.jianshu.com/p/840169ba92e6


Source: Jane Book


Brief book copyright belongs to the author, any form of reprint please contact the author to obtain authorization and indicate the source.