A brief introduction to nuxt.js
Nuxt.js is a server rendering framework based on vue.js.
Schematic diagram of Vue SSR
The advantage of Nuxt. Js
- You don’t have to worry about routing, just create.vue files at the corresponding folder level
- Regardless of the data transfer, Nuxt requests data asynchronously before the template output (with the introduction of the AXIos library) and further encapsulates VUex
- Webpack is built in, eliminating the need to configure webpack, and NuxT packages corresponding files according to the configuration
The following illustration illustrates how Nuxt.js applies a complete server request to the render (or user pass)<nuxt-link>
Switch route render page) :
-
Incoming Request: indicates that the browser sends a Request
-
NuxtServerInit: The server receives the request and checks whether the configuration item nuxtServerInit is currently available. If so, it executes this method first. This method is used to manipulate vuex
-
Middleware: This is a piece of middleware associated with routing that can do any desired function
-
Validate () : verifies with advanced dynamic routes, such as whether page A is allowed to jump to page B, and whether it can jump to other pages if it fails the verification
-
AsyncData ()&fetch() : Fetch data. AsyncData () takes data that is used to render vUE components, and FETCH is usually used to modify vuex data
-
Render: apply colours to a drawing
-
Naviage: If a non-server route is initiated, the Middleware — Render process is performed
The main description
asyncData
The asyncData method is a nuxt.js extension to Vue. Is called before each initialization of a component (page component only). So this method has no way of referring to the component instance object through this. It can be invoked before a server or route is updated. The asyncData method can be used to retrieve data and return it to the current component.
asyncData (context) {
return { project: 'nuxt'}}Copy the code
What are asyncData context parameters?
- App: App object
- Store: Store, you can get the data in the store
- Route: You can get the parameters and so on
- Params: url path parameter, mainly to obtain the ID
- Query: can be understood as the parameter after the question mark in the URL
- Env: running environment
- IsDev: Whether it is a development environment
- IsHMR: Whether it is a hot update
- Redirect: Redirects
- Error: error
What can asyncData do?
Create renderer
Nuxt Renderer uses the vue-server-renderer plugin to create the renderer and parse the bundle files made by WebPack
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.
async fetch({ store, params }) {
const { data } = axios.get('http://abc.com/api/stara')
store.commit('setStars/set', data)
}
Copy the code
Fetch or asyncData methods are deprecated in layouts and components.
What does server.js do
Each user accessing a Vue page through the browser is a completely new context, but on the server, the application is always running once it is started, and each user request is processed in the same application context. In order not to string data, a new app, store and router need to be created for each SSR request.
Let’s focus on the last part, the asyncData part
The matching Component is first returned based on the URL call in the context
It then iterates through each component, promisify() according to the asyncData configuration of the component and assigns the context object to the asyncData method
The promisify() method takes two arguments: the asyncData() method configured in the first component; The second is the context object mounted to the new VUE instance
After execution, the method synchronizes the obtained data to the data defined in the page. AsyncData is only called once on the first screen, and the subsequent interaction is handed over to the client
Use of window and Document objects
When developing nuxT projects, it is inevitable that we will use window or Document to retrieve DOM elements. An error is reported if used directly in a file. That’s because window or document is something on the browser side that the server side doesn’t have. Solution: we only need to use the place through the process. The browser/process server to judge
if (process.browser) {
// Run code in the browser
}
Copy the code
nuxtServerInit
If the nuxtServerInit method is specified in the state tree, it is called by nuxt.js with the page context object as the second argument (if called by the server). This method is useful when we want to transfer some data from the server to the client.
For example, suppose we can access the current logged-in user through req.session.user in the server’s session state tree. To pass the logged-in user information to the client’s state tree, we simply update store/index.js as follows:
actions: {
nuxtServerInit ({ commit }, { req }) {
if (req.session.user) {
commit('user', req.session.user)
}
}
}
Copy the code
Performance optimization
keep-alive
Nuxt added this functionality in 1.2.0. In the layouts/default. Vue:
<template>
<Nuxt keep-alive/>
</template>
Copy the code
Server render application
Mounted does not support server rendering. Client-only components are not displayed in server rendering.
API data and page structure can be split reasonably through related features. Data and structure required by the first screen can be obtained and rendered by the server, while non-first screen data and structure can be obtained and rendered by the client.
<template>
<div>
<! -- Top banner -->
<banner :banner="banner" />
<! -- Not required for the first screen, using client-only components to not render on the server -->
<client-only>
<! List -- - >
<prod-list :listData="listData"/>
</client-only>
</div>
</template>
Copy the code
Component caching
The DOM structure of the rendered component is stored in the cache and periodically refreshed. The validity period of the DOM structure of the component is obtained from the cache to reduce the time required to generate DOM structure.
Applies to components that have the same structure or only a few transformations after rendering and do not affect the context.
The nuxt.config.js configuration item is modified
const LRU = require('lru-cache')
module.exports = {
render: {
bundleRenderer: {
cache: new LRUCache({
max: 1000.// Cache queue length
maxAge: 1000 * 60 // Cache for 1 minute})}}}Copy the code
For vUE components that need to be cached, add the name and serverCacheKey fields to determine the unique key value for the cache.
export default {
name: 'componentName'.props: ['item'].serverCacheKey: props= > props.item.id
}
Copy the code
-
It doesn’t make much sense to cache components that depend on too many global states, or that have too many state values that the cache will overflow because of frequent Settings.
-
A component cache is a cache of DOM structures. Code logic in a created hook, for example, is not cached and will not be executed if the logic affects changes up or down. This component is also not suitable for caching.
Page global cache
When the entire page has nothing to do with user data and the dependent data is basically unchanged, the whole page can be cached to reduce the page acquisition time.
The whole page caching requirement is that when initializing a project using nuxt.js scaffolding tool creation-NuxT-app, the integration server framework such as Express and KOA must be selected so that it can be extended by server-side middleware.
For the nuxT framework, the scaffolding initialization is completed, and the framework is highly encapsulated in the res.end() function rendered by the Vue server, server middleware/ Page-cache.js
import LRUCache from "lru-cache";
const cache = new LRUCache({
maxAge: 1000 * 60 * 2.// Valid for 2 minutes
max: 100 // Maximum number of caches
});
export default function(req, res, next) {
// The local development environment does not do page caching
if(process.env.NODE_ENV ! = ="development") {
try {
const cacheKey = req.url;
const cacheData = cache.get(cacheKey);
if (cacheData) {
return res.end(cacheData, "utf8");
}
const originalEnd = res.end;
res.end = function(data) { cache.set(cacheKey, data); originalEnd.call(res, ... arguments);console.log(data);
};
} catch (error) {
console.log(`page-cache-middleware: ${error}`);
next();
}
}
next();
}
Copy the code
The nuxt.config.js configuration item is modified to introduce server middleware
serverMiddleware:[
{ path: '/app'.handler: '~/middleware/page-cache'}]Copy the code
Server-side rendering middleware (serverMiddleware) vs middleware (Middleware). Do not associate it with the client or SSR Vue called before each routeroutes middleware
Confusion.serverMiddleware
Only in thevue-server-renderer
Previously run on the server side, it can be used for server-specific tasks, such as processing API requests or service assets.
The problem
Axios on the server does not automatically carry cookies
Add an interface to the AXIos wrapper to inject cookies, and router-middleware will fetch and inject cookies from Context.headers. Cookie
data
- Nuxt community
- The original link