Recently, I was doing some requirements for the homepage of the website, which needed to support SEO, and then I used NUXT to do server-side rendering

A preliminary introduction

See the official documentation first to understand the basic features of nuxt.cn, generally used and vue is not much different, there are the following differences

1. Nuxt routing depends on the name of the files in the page folder. There is no need to configure routing files.

2. Server-side rendering involves the problem of dynamic data request. If the interface needs to be called in the page that needs server-side rendering, asyncData can be used to complete the call

3. Nuxt’s plugin system is frequently used in the whole process of using NuxT. Almost every reference to a third-party plugin needs to add a JS to the plugin, and the plugin can get the context object

Ii. Modules used in the project

1. @ nuxtjs/axios,

I was wrestling with axios and @nuxtjs/axios, but I chose @nuxtjs/axios, which is a little easier to use. In this project, we write an API file and pass it into $axios, then use plugin inject API under this and app to facilitate subsequent interface calls

api/api.js export default ($axios) => ({ getList(params, config) { return $axios.$get('/api/list') } plugin/axios-api.js import api from '~/api/api.js' export default ({ $axios }, inject) => { const axiosApi = api($axios) for (const [key, value] of Object.entries(axiosApi)) { inject(key, Value)}} nuxt-config.js to import this jsCopy the code
// Use async asyncData({app}) {let result = await app.$getList()} // Use async getLists() {let res = } plugin/axios.js import {Message} from 'elemental-ui' export default function ({$axios, redirect, store, app }) { $axios.onRequest((config) => { }) $axios.onResponse((res) => { }) $axios.onError((error) => { if (response && response.status ! == 200) {if (response.status === 401) {redirect(redirect)} if (response&& response.config.server) {store.com MIT ( 'setError' (error && error. The message) | | 'network error, Please try again later ')} else {Message. Error (app. I18n. T ((error && error. The Message) | | 'network error, please try again later))}}})}Copy the code

Since the interface error in asyncData cannot be prompted by popup, I saved the error information in AXIos interception function in VUex, and then checked whether there was any error information to pop up in VUex when the page was rendering. In order to remove the error information in time, Clear vuEX error messages in the closed callback function of Element’s Message component

openServerError() {
      const { error } = this.$store.state
      if (error) {
        const that = this
        this.$notify({
          type: 'error',
          message: error,
          onClose() {
            that.notifyClose()
          },
        })
      }
    },
    notifyClose() {
      this.$store.commit('deleteError')
    },

Copy the code

2.nuxt-i18n

Nuxt-i18n is used for internationalization of the project. The nuxT-I18N configuration is simple to follow in the official documentation. Since nuxT internationalization is followed by language parameters by default, there is a requirement that you want to change the cookie to refresh the page, and the page is automatically positioned to the corresponding language page. The idea was to add “en” to the middleware if there is no en in the English path and remove the “en” from the Chinese path. Finally, using the Redirect in middleware often causes web pages to crash and redirect too many times. I found several properties that worked together to achieve my purpose

i18n: { locales: [ { code: 'zh', iso: 'zh', file: 'cn.js' }, { code: 'en', iso: 'en', file: 'en.js', }, ], defaultLocale: 'zh', vueI18n: { fallbackLocale: 'zh', silentTranslationWarn: Seos: true, lazy: true, langDir: 'i18n/', // detectBrowserLanguage { useCookie: true, cookieKey: 'cookieName', alwaysRedirect: true, cookieDomain: 'Your domain',},}, also encountered the problem of element introducing internationalization on demand, Import ElementLocale from 'element-ui/lib/locale' elementlocale.i18n ((key, value) => app.i18n.t(key, value))Copy the code

3.@nuxtjs/device

Check whether the current device is PC or mobile, and check whether it is Windows, MAC, isAndroid or iPhone. Note that in iPhone instance.$device.isMacOS is also true

4.dayjs

This is a lightweight JS time processing NPM package, the original use of moment later, the team leader analysis of the code performance said that the package is too large, accounting for 25% of the entire code, so changed to dayJS can also meet the needs of the use of almost the same as moment

5.vue-observe-visibility

Detect the scrolling position of the browser and wait for the page to scroll to that position before invoking the interface

6.nuxt-helmet

7.nuxt build –analyze

Use “build:check”: “nuxt build –analyze” to analyze the code

Three. Encountered pits

1. Nuxt has a static folder that can be accessed under the root directory, but I added a file under the root directory, but I still cannot access it. Nuxt builds static without packing it

2. The list page on the mobile end needs scrolling loading, which uses Element’s InfiniteScroll infinite scrolling. This has requirements on style, and the scrolling loading area needs to be set to the height, which will cause the page to slide to the bottom before the data is loaded

3. Nuxt uses the plugin named xxx.client.js, so the plugin will only render if it is inside. At that time, there were three places in the project using the perfect-Scrollbar plug-in, and the last two places were rendered. The first place was never rendered, and the second place was not rendered until it was discovered that the plug-in was used.

4. Tips

Be sure to study the documentation when you encounter problems. Mature frameworks and modules basically have what you want, and you don’t have to build your own wheels