Vue-based server-side rendering framework Nuxt.js case description

Keywords: Front-end Vue axios npm network

background

To develop a new official website (education company), the website needs to consider drainage, promotion, keyword search ranking, so the website needs to do SEO.Vue.js is a framework for building client applications that, by default, can output Vue components in a browser for DOM generation and operationsDOM, like this client-side rendering method, is not conducive to SEO optimization, especially when the website uses ajax to get news lists, news details and other information. Baidu crawlers do not capture, so the official website needs to consider a server-side rendering (SSR) page.

Introduction to Nuxt.js

Building a server-side rendering application from scratch is quite complex.Fortunately, using Nuxt.js makes this all easier.Nuxt is a higher-level framework based on the Vue ecology, which provides an extremely convenient development experience for developing service-side rendered Vue applications. The main advantages of server-side rendering (SSR) are:

  1. Better SEO, because search engine crawler grab tools can directly view fully rendered pages
  2. Faster content arrival time (time-to-content), especially for slow network conditions or slow devices.

Case Description

All of the following descriptions list some key configurations of Nuxt.js around the functionality required by the website, not all of the functionality of Nuxt.js.
DEMO address: HelloNuxt

1. html header

Do SEO optimization, not only consider server-side rendering, but also the Met tags of pages, such as title, description, keywords, etc.
The default global configuration is placed in the nuxt.config.js file:

  head: {
    title: '*******Official Web',
    meta: [
      { hid: 'description', name: 'description', content: 'Any descriptive information' },
      { hid: 'keyword', name: 'keyword', content: 'Keyword 1,Keyword 2......' }
    ]
  }

For example, the Official Web News Detail Page has a special title or descriptive information, which can be set in this way

<template>
  <div class="content">
    <h3>News Details Page</h3>
</template>

<script>
export default {
  data () {
    return {
      data: {
        title: 'News Title',
        description: 'Descriptive Information'
      }
    }
  },
  head () {
    return {
      title: this.data.title,
      meta: [
        { hid: 'description', name: 'description', content: this.data.description },
      ],
    }
  }
}
</script>

2. Layout

Add a layout file to the layouts directory to place the common part of the page in the layout file. The default layout file is default.vue. Don't forget to add <nuxt/>components to the layout file to display the main content of the page. Suppose we create a layout with a dark theme and save it to layouts/dark.vue

<template>
  <div>
    <div>Dark Layout Template</div>
    <nuxt/>
  </div>
</template>

If you want to use a page with a custom layout, you need to point out in the page:

<template>
<!-- Your template -->
</template>
<script>
export default {
  layout: 'dark'
}
</script>

3. Page Routing

There is no need to write a routing file, and Nuxt automatically generates the routing configuration for the vue-router module based on the pages directory structure. Suppose the file structure is as follows:

pages/
--| index.vue
--| news/
-----| index.vue
-----| _id.vue
-----| detail/
---------| _id.vue

Defining dynamic routes with parameters in Nuxt.js requires creating corresponding Vue files or directories prefixed with underscores. The routes automatically generated by Nuxt.js are configured as follows:

router: {
  routes: [
    {
      path: '/',
      component: 'pages/index.vue',
      name: 'index'
    },
    {
      path: '/news',
	  component: 'pages/news/index.vue',
      children: [
        {
          path: ':id',
          component: 'pages/news/_id.vue',
          name: 'news-id'
        },
        {
          path: 'detail/:id',
          component: 'pages/news/detail/_id.vue',
          name:'news-detail-id'
        }
      ]
    }
  ]
}

There is a dynamic route (_id.vue) under the news directory, which mainly considers pageNum passed by page-flipping of news lists, or page parameter? pageNum=1

4. Asynchronous data

Nuxt.js adds the asyncData method, which allows you to get or process data asynchronously before setting up data for a component.The asyncData method is called before each load of the component (page component only).It can be invoked on the server side or before routing updates.

<template>
  <div>
    <h3>News Center</h3>
    <ul>
      <li v-for="item in news">
        <NLink :to="`/news/detail/${item.id}`">{{item.name}}</NLink>
      </li>
    </ul>
  </div>
</template>
<script>
import axios from 'axios' 
export default {
  asyncData ({ params, error }) {
    return axios.get(`eg/xxxx/news?pageSize=10&pageNum=${params.id || 1}`).then(res => {
      return {
        news: res.data.news,
        page: {
          total: res.data.total
        }
      }
    })
  }
}
</script>

Nuxt.js returns the data returned by the data fusion component data method from asyncData to the current component as well.

5. vuex state tree

This module may not be commonly used on corporate websites, but I'd like to take it out and say that Nuxt.js allows you to have a store directory with each file corresponding to the module. Direct example, store/index.js:

export const state = () => ({
  news:[]
})

export const mutations = {
  SET_VISIT (state, data) {
    state.news = data
  }
}

export const getters={
  getNews(state){
    return state.news
  }
}

You can have the store/other.js module:

export const state = () => ({
  list: []
})

Nuxt.js automatically initializes the store object based on the module defined in the store directory and then binds it to the framework; using it in components is basically the same as using it in Vue.js

import {mapGetters } from 'vuex'
export default {
  computed: {
    otherList () {
      return this.$store.state.other.list
    },
...mapGetters({
    news: 'getNews'
  })
  }
}

6. Plug-ins

Using a third-party module, you can import npm directly and then introduce it into your components, such as the example of axios in the asynchronous data above.
Using vue plug-ins, such as element-ui, first add the file, plugins/element-ui.js

import Vue from 'vue'
import Element from 'element-ui'
Vue.use(Element)

Then configure the plugins in nuxt.config.js as follows:

module.exports = {
  css: [
    'element-ui/lib/theme-chalk/index.css',
  ],
  plugins: [{ src: '@/plugins/element-ui' }],
  build: {
    extractCSS: { allChunks: true }
  }
 }

Once the configuration is complete, you can use the components of the element-ui.Common css files in the project can also be introduced in the css array here.
build/extractCSS is configured here to help you quickly separate CSS from HTML. If allChunks=false, style files are not introduced as link s, but are loaded directly into the <style /> tag on the page.

7. Other

  1. If sass is required in your project, you can import the npm package directly without any additional configuration.
  2. The Nuxt.js team created a scaffolding tool that directly generated the project: NPX create-nuxt-app <project name>

Posted by sledgeweb on Sun, 19 Apr 2020 00:51:45 -0700