It took three months to write the project with NUxT, and I wrote an official website from 0 to 1: www.nancal.com/.

Sort out the problems and skills you encounter for later review; Nuxt official website: nuxtjs.org/

The basic framework is set up according to the official website: nuxtjs.org/docs/get-st… , and then do some basic configuration and folder structure configuration on this framework

The overall structure of the project looks something like this, using nuXT2

  1. Interface Tuning Configuration (AXIOS)
  2. Some of the ElementUI styles are referenced
  3. Use localStorage or sessionStorage
  4. Encapsulate unified interface request methods for easy maintenance

Interface linkage configuration

// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins plugins: [ '@/plugins/element-ui', '@/plugins/axios.js', '@/plugins/api-plugin', '@/plugins/bus-plugin', '@/plugins/my-mixin-plugin', '@/plugins/breadcrumb', '@/plugins/global-componten', '@/plugins/poly', {src: '@/plugins/persistedState.js'} // '@/plugins/i18n.js' ],Copy the code
//plugins/axios export default function ({store, redirect, req, router, $axios, error }) { $axios.interceptors.request.use(config => { return config; }); $axios. Interceptors. Response. Use (response = > {/ / processed... }, error => {// handle accordingly... }); $axios.onError(err => {// handle the error accordingly... }); }Copy the code
//plugins/api-plugin.js/ Plugins /api-plugin.js import apis from '@/ API /index'; plugins/api-plugin.js import apis from '@/ API /index'; export default (ctx, inject) => { var apiObject = {}; for (var i in apis) { apiObject[i] = apis[i](ctx.$axios); } / / document: / / https://www.nuxtjs.cn/guide/plugins inject: into the context of a service, vue instance, inject in vuex (' API 'apiObject); };Copy the code
// API /index.js // API /index module export as an object, // API module entry // modulesFiles = require.context('./apilist', true, /\.js$/); const modules = modulesFiles.keys().reduce((modules, modulePath) => { const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1'); const value = modulesFiles(modulePath); modules[moduleName] = value.default || value; return modules; }, {}); export default modules; export function getFullUrl(path) { if (process.client) { console.log(process.env.VUE_APP_BASE_API + path, 'process.env.VUE_APP_BASE_API + path'); return process.env.VUE_APP_BASE_API + path; } console.log(process.env.VUE_APP_SERVER_HOST + path, 'process.env.VUE_APP_SERVER_HOST + path'); return process.env.VUE_APP_SERVER_HOST + path; }Copy the code

Some of the ElementUI styles are referenced

As the Elementui website says, you can import on demand

Use localStorage or sessionStorage

If (process.client) {localstorage.getitem... }Copy the code

Take a look at the life cycle of nuXT

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

Nuxt.js is simply a generic framework for vue.js, most commonly used for SSR (server-side rendering). Vue. Js was originally developed for SPA (single-page applications), but with the popularization of technology, many people want to develop multi-page applications with Vue and complete rendering on the server side. At this time, the nuxt.js framework appeared, she simplified the difficulty of SSR development. We can also generate static HTML from our vUE projects directly by command.

Vue’s life cycle all runs on the client side (browser), while Nuxt’s life cycle some runs on the server side (Node), client, or even both:

** This is the nuxt.js life cycle flow chart. The red box shows the life cycle of Nuxt (running on the server), the yellow box shows the life cycle of NuxT (running on the server), and the green box shows the life cycle of NuxT (running on the client)

** Because the red box and the yellow box do not have the Window object, so can not directly use the Window, will report an error **

The following details each hook function execution:

incoming request

At this stage, the server receives the request and begins the process

nuxtServerInit

1. Server initialization 2. Use 3 only in store/index.js. Used to store data into VUex before rendering the page

middleware

Some pre-defined middleware is executed in this phase, and self-defined middleware is executed in this phase

validate

You can configure a validation method to verify the validity of dynamic routing parameters in the corresponding page component. (Please refer to official documentation for specific implementation)

asyncData

This method allows you to retrieve data asynchronously before rendering components. Just as you would get data with Created in vue components, the difference is that asyncData is performed on the server side. Note also that asyncData is only called once on the first screen (before the page is rendered, so it can’t be triggered by an event).

fetch

The FETCH method is used to populate the application’s store data before rendering the page, similar to the asyncData method except that it does not set the component’s data. If a page component sets the fetch method, it will be called before each load of the component (on the server or before switching to the destination route). The first parameter of the FETCH method is the context object of the page component. We can use the FETCH method to fetch data to populate the application’s state tree. To make the fetch process asynchronous, you need to return a Promise, and nuxt.js waits for that Promise to complete before rendering the component. Note that you can use this to get the component instance during the FETCH phase, which is called before the component is initialized (as if the fetch function is also executed once between Created and beforeMount)

If you want to call and manipulate store in fetch, use store.dispatch, but be sure to wait internally for the operation to end with async/await:

Async fetch({store, params}) {await store.dispatch('GET_STARS')} copies codeCopy the code

render

This phase starts preparing the client rendering, and if there is a nuxt-link jump in the process, it falls back to the Middleware phase and executes again

BeforeCreat and Created phases

This is similar to the vUE hook function, with one minor difference. Vue’s hooks are executed only on the client side, while NUxT’s hooks are executed on both the client and server side

Other phases

The subsequent phases are performed in the client, such as the beforeMount and Mounted phases, and so on

The part of the hole that you stepped on

Process. env[an environment variable] cannot be used directly in nuxt.config.js

The Dotenv plug-in is required

const envFileName = `.env.${process.env.customMode}`; const dotenvObj = require('dotenv').config({ path: envFileName}).parsed; Copy the codeCopy the code

Configuration in package.json is how I introduced it

"Scripts ": {"dev": "cross-env customMode=development nuxt --open",} copy the codeCopy the code

The final SEO score looks something like this

Of course, seo in addition to do webpack optimization configuration, more is the need to pay attention to the corresponding syntax in the component, image embedding optimization (NUXT official website gives some image optimization solutions), including the interface in the image in HTTP request to be as small as possible, etc..

Other thought of to add……