Vue. Js is one of the most popular front-end frameworks at present, and Nuxt.js is a server rendering framework launched for VUe. js, through highly customized configuration and concise API, developers can quickly carry out the development of server rendering projects, this article will make a brief introduction to nuxT. js framework.
Server side rendering
Server Side Render is not a new concept, in the days before single-page applications (SPA) became popular, pages were rendered on the Server and delivered to the browser. When the user needs to access a new page, he needs to request the server again to return the new page.
In order to optimize the experience, developers begin to choose to use JavaScript to complete the rendering process in the front end. The method of separating the front end from the back end makes the back end more focused on data, while the front end focuses on processing and display. The interaction between the front end and the back end is completed through well-designed API and Ajax technology. Frameworks such as jQuery, react. js, vue. js, angular. js have emerged.
These frameworks bring great convenience to developers, but for forums, information sites, or corporate official websites, search engine optimization (SEO) requirements are very strong, and front-end rendering technology is not enough to meet their needs. If the search engine can not output their own content, then the value of the site will be greatly affected, to solve this kind of problem, or rely on server-side rendering.
This article introduces nuxt.js, a server-side rendering solution for vue.js. After the launch of Vue.js, its data-driven and component-oriented ideas, as well as its simple and easy-to-use features have brought great convenience to developers. The vue-server-renderer officially provided by Vue.js can be used for server-side rendering, but additional workload is needed, and the development experience still needs to be improved. After nuxt.js was launched, this problem was well solved.
A brief introduction Nuxt. Js
Nuxt.js is a general-purpose application framework based on vue.js. Nuxt.js presets the configuration required to develop server-side rendered applications using vue.js, and can generate static sites with one click. At the same time, nuxt.js hot loading mechanism can make it very convenient for developers to carry out website development.
Nuxt.js was released on October 25, 2016. It has been online for less than a year, but it has already been well received. The latest stable version is 0.10.7, and the nuxt.js community is still in beta for version 1.0.
Simple to fit
The vuE-cli tool for vue.js makes it easy to initialize vue.js projects using ready-made templates, and the Nuxt.js team has provided templates for initializing nuxt.js projects. After installing vue-CLI, just type in the command line
vue init nuxt/starter <projectName>Copy the code
To complete the project creation, go to the project directory and execute the following command:
npm install
npm run devCopy the code
Nuxt.js will use port 3000 to run the service. Type http://localhost:3000 in your browser and you’ll see a raw page with the nuxt.js logo.
Project directory
With a simple Hello World project completed, let’s take a closer look at nuxt.js. After entering the nuxt.js project, the project directory is as follows:
Here is a brief introduction to the functions of each directory:
-
.nuxt/ : Used to store the nuxt.js core library file. For example, you can find the server.js file in this directory, which describes the logic for nuxt.js to render servers (see the next section “Nuxt.js Rendering Process”). The router.js file contains an automatically generated routing table.
-
Assets / : Stores static resources. Resources in this directory are built using Webpack.
-
Components / : Stores various components in the project. Note that only files in this directory can be called components.
-
You can also use this directory to create a unified global page layout or error page layout. If you want to render routing pages in the Pages directory in your layout, you need to tag the layout file with a
tag. -
Middleware / : Places custom middleware that is called before components are loaded.
-
Pages / : In this directory, nuxt.js generates vue-Router routes based on the directory structure, as described below.
-
Plugins / : This is where you can place custom plug-ins to run before the root Vue object is instantiated. For example, buried logic in a project can be packaged as a plug-in, placed in this directory and loaded in nuxt.config.js.
-
Static / : Static resources that are not built using Webpack are mapped to the root path, such as robots.txt
-
Store / : Stores the Vuex status tree.
-
Nuxt.config. js: nuxt.js configuration file, see below.
Nuxt.js rendering process
Nuxt.js performs server-side rendering through a series of methods built on vue.js, as follows:
-
Call the nuxtServerInit method
The nuxtServerInit method is the first to be called when a request comes in, which can be used to pre-store server data such as logged-in user information. Alternatively, asynchronous operations can be performed in this method and wait for the data to be parsed and returned.
-
Middleware layer
After the first step, the request goes to the Middleware layer, where there are three steps:
- read
nuxt.config.js
In the globalmiddleware
Field and invoke the appropriate middleware method - Matches and loads corresponding to the request
layout
- call
layout
和page
Middleware methods of
- read
-
Call validate method
In this step, you can validate the request parameters or the data sent by the server in the first step. If the validation fails, a 404 page will be thrown.
-
Call the FETCH and asyncData methods
Both methods are called before the component is loaded and have different responsibilities. AsyncData is used to asynchronously initialize the component data, while FETCH focuses on asynchronously retrieving the data and modifying the state in Vuex.
We can see the following methods in the source code util.js for nuxt.js:
export function applyAsyncData (Component, asyncData = {}) {
const ComponentData = Component.options.data || noopData
Component.options.data = function () {
const data = ComponentData.call(this)
return{... data, ... asyncData } }if (Component._Ctor && Component._Ctor.options) {
Component._Ctor.options.data = Component.options.data
}
}Copy the code
This method will be called after the asyncData method is called. It can be seen that the data obtained by the component from the asyncData method will be merged with the data obtained by the component’s native data method, and will still be returned in the data method. Therefore, The asyncData method is an extension of the native data method.
After the above four steps, it’s time to render the components. The whole process can be represented as follows:
(Photo credit: nuxt.js official website)
As mentioned above, in the.nuxt directory, you’ll find the server.js file, which encapsulates nuxt.js’s server-side rendering logic, including a complete chain call to the Promise object that completes the entire server-side rendering steps described above.
Some tips for using nuxt.js
Nuxt. Config. Js configuration
Nuxt.config. js is the nuxt.js configuration file. You can configure the nuxt.js project by setting a series of parameters.
-
Head: You can configure the global head in this configuration item, such as defining the title of the site, meta, importing third-party CSS, JavaScript files, etc. :
head: { title: 'People's Shop'.meta: [{charset: 'utf-8' }, { name: 'viewport'.content: 'width=device-width, initial-scale=1' }, { name: 'applicable-device'.content: 'pc,mobile'},].link: [{rel: 'stylesheet'.type: 'text/css'.href: 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css'}].script: [{src: 'https://code.jquery.com/jquery-3.1.1.min.js'}, {src: 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js'}},Copy the code
-
build: This configuration item is used to configure the build rules of the nuxt. js project, that is, the build configuration of Webpack, such as importing third-party modules through the Vendor field, configuring the Webpack plug-in through the Plugin field, and customalizing the Webpack loader through the loaders field. Usually we introduce the AXIos module in the vendor field of the build to make HTTP requests in the project (Axios is also the official recommended HTTP request framework for vue.js).
build: { vendor: ['core-js'.'axios'].loaders: [{test: /\.(scss|sass)$/.use: [{ loader: "style-loader" }, { loader: "css-loader" }, { loader: "sass-loader"}]}, {test: /\.(png|jpe? g|gif|svg)$/.loader: 'url-loader'.query: { limit: 1000.name: 'img/[name].[hash:7].[ext]'}}, {test: /\.(woff2? |eot|ttf|otf)(\? . *)? $/.loader: 'url-loader'.query: { limit: 1000.name: 'fonts/[name].[hash:7].[ext]'}}}]Copy the code
-
CSS: In this configuration item, a global CSS file is introduced, after which each page is introduced.
-
Router: You can configure basic routing rules and middleware. For example, you could create a middleware to fetch user-Agent and load it there.
-
Loading: Nuxt.js provides a set of in-page loading progress indicators, which can be configured to color, disable, or configure a custom loading component.
-
Env: This is where you can configure global variables to be shared between the server and the client.
Directory as route
Nuxt.js defines a set of automated build rules on vue-Router based on the directory structure of Pages. For example, we have the following directory structure:
This directory contains one basic route (with no parameters) and two dynamic routes (with parameters). Nuxt.js generates the following routing configuration table (found in the router.js file in the.nuxt directory) :
routes: [
{
path: "/".component: _abe13a78,
name: "index"
},
{
path: "/article/:id?".component: _48f202f2,
name: "article-id"
},
{
path: "/:page".component: _5ccbb43a,
name: "page"}]Copy the code
For the article-id route, the path has :id? Parameter indicating that this is an optional route. To make it mandatory, you must add the index.vue file in the article directory.
Here’s another example:
Nuxt.js generates nested routes for us because there are files and folders with the same name. The generated route structure is as follows. When used, we need to add the
routes: [
{
path: "/article".component: _f930b330,
children: [{path: "".component: _1430822a,
name: "article"
},
{
path: ":id".component: _339e8013,
name: "article-id"}}]]Copy the code
In addition, nuxt.js can also set dynamic nested routines, as described in the nuxt.js documentation.
conclusion
Although nuxt.js is a very young framework, it has a lot of problems to be improved, but it has provided great convenience for vue.js developers to build server-side rendering projects. We look forward to nuxt.js 1.0 release, will bring us more practical new features.
Author: Li Ren Profile: Member of technical team of Commercial Operation Center of People’s Net.
This article is the author’s personal view only, does not represent the people’s net position.
This article is published on the wechat public account of “People’s Net Technical Team”. Scan the code to subscribe immediately: