Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of Vue.js Server rendering in Nuxt

2025-03-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly shows you "sample analysis of Vue.js server rendering in Nuxt", which is easy to understand and well organized. I hope it can help you solve your doubts. Let the editor lead you to study and learn the article "sample analysis of Vue.js server rendering in Nuxt".

Server rendering

Server-side rendering (Server Side Render) is not a new concept. When single-page applications (SPA) were not popular, pages were rendered through the server and passed to the browser. When users need to visit a new page, they need to request the server again to return to the new page.

In order to optimize the experience, developers began to use JavaScript to complete the rendering process at the front end, using the means of separating the front end and the front end to make the back end more focused on data, while the front end focused on processing and display, and completed the interaction between the front end and back end through well-designed API and Ajax technology. JQuery, React.js, Vue.js, Angular.js and other frameworks emerged as the times require.

These frameworks bring great convenience to developers, but for some forums, information sites, or official websites of enterprises, they have a strong demand for search engine optimization (SEO), and front-end rendering technology can not meet their needs. If you can not output your own content through the search engine, then the value of the site will be greatly affected, to solve this kind of problem, or rely on the server rendering.

This article introduces Vue.js 's server-side rendering solution, Nuxt.js. After the launch of Vue.js, its data-driven and component-based ideas, as well as its simple and easy-to-use features have brought great convenience to developers. Vue-server-renderer officially provided by Vue.js can be used for server rendering, but it requires additional workload, and the development experience still needs to be improved. After the launch of Nuxt.js, this problem has been well solved.

Introduction to Nuxt.js

Nuxt.js is a general application framework based on Vue.js. Nuxt.js presets various configurations needed to develop server-side rendering applications using Vue.js, and can generate static sites with one click. At the same time, the hot loading mechanism of Nuxt.js makes it very convenient for developers to develop websites.

Nuxt.js was released on October 25, 2016 and has been online for less than a year, but it has been widely praised. The latest stable version is 0.10.7. Internal testing of version 1.0 is still under way, and the Nuxt.js community is gradually improving. The official website already supports Chinese documents.

Easy to get started with

Vue.js 's vue-cli tool makes it easy for us to initialize the Vue.js project using ready-made templates, and the Nuxt.js team has provided us with a template for initializing the Nuxt.js project. After installing vue-cli, just type on the command line

Vue init nuxt/starter

You can complete the creation of the project, and then go to the project directory and execute the following command:

Npm installnpm run dev

Nuxt.js will run the service using port 3000, and type http://localhost:3000 in the browser to see the original page of logo with Nuxt.js.

Project catalog

After completing a simple Hello World project, 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 description of the role of each directory:

.nuxt /: used to store the core library files of Nuxt.js. For example, you can find the server.js file in this directory, which describes the logic of server-side rendering of Nuxt.js (see the next paragraph, "rendering flow of Nuxt.js"). The router.js file contains an automatically generated routing table.

Assets/: used to store static resources, the resources in this directory are built using Webpack.

Components/: stores the various components in the project. Note that only files in this directory can be called components.

Layouts/: create a custom page layout under which you can create a unified layout of global pages, or error page layouts. If you need to render the routing page in the pages directory in the layout, you need to tag it in the layout file.

Middleware/: place custom middleware that is called before the component is loaded.

Pages/: under this directory, Nuxt.js will generate vue-router routes based on the structure of the directory, as detailed below.

Plugins/: you can place custom plug-ins in this directory to run before the root Vue object is instantiated. For example, you can encapsulate the buried point logic in a project into a plug-in, place it in this directory, and load it in nuxt.config.js.

Static/: static resources built without Webpack will be mapped to the root path, such as robots.txt

Store/: stores the Vuex state tree.

Nuxt.config.js: the configuration file for Nuxt.js, see below.

Rendering process of Nuxt.js

Nuxt.js performs server rendering through a series of methods built on Vue.js. The specific process is as follows:

Call the nuxtServerInit method

When a request is entered, the nuxtServerInit method is called first, which allows you to save the server's data in advance, such as logged-in user information, and so on. In addition, you can also perform asynchronous operations in this method and wait for the data to be parsed and returned.

Middleware layer

After the first step, the request goes into the Middleware layer, where there are three steps:

Read the configuration of the global middleware field in nuxt.config.js and call the corresponding middleware methods to match and load the corresponding layout calling layout and page middleware methods corresponding to the request

Call the validate method

In this step, you can verify the request parameters, or the data sent by the server in the first step. If the verification fails, a 404 page will be thrown.

Call the fetch and asyncData methods

These two methods are called before the component is loaded, and their responsibilities are different. AsyncData is used to initialize component data asynchronously, while fetch method focuses on modifying the state in Vuex after getting data asynchronously.

We can see the following methods in the source code util.js of 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}}

This method will be called after the asyncData method is called. You can see 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 eventually be returned in the data method, so it is concluded that the asyncData method is actually an extension of the native data method.

After the above four steps, the next step is the work of the rendering component, which can be shown in the following figure:

(photo source: Nuxt.js official website)

As mentioned above, in the .nuxt directory, you can find the server.js file, which encapsulates the server-side rendering logic of Nuxt.js, including a complete chain call of Promise objects, thus completing the entire server-side rendering steps described above.

Some skills of using Nuxt.js

Configuration of nuxt.config.js

Nuxt.config.js is the configuration file of Nuxt.js. You can configure the Nuxt.js project by setting a series of parameters. Instructions for this file can be found on Nuxt.js 's official website. Here are some common configurations:

Head: you can configure the global head in this configuration item, such as defining the title and meta of the website, introducing third-party CSS, JavaScript files, and so on:

Head: {title: 'people's shops', 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'}]}

Build: this configuration item is used to configure the construction rules of the Nuxt.js project, that is, the construction configuration of Webpack, such as introducing third-party modules through the vendor field, configuring the Webpack plug-in through the plugin field, customizing the Webpack loader through the loaders field, and so on. Usually we introduce the axios module into the vendor field of build to make HTTP requests in the project (axios is also the HTTP request framework officially recommended by 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]'}]}

Css: in this configuration item, a global CSS file is introduced, after which each page is introduced.

Router: you can configure the basic rules of routing and the configuration of middleware here. For example, you can create a middleware to get User-Agent and load it here.

Loading: Nuxt.js provides a set of in-page load progress indicator components where you can configure colors, disable, or configure custom load components.

Env: global variables that can be shared on the server and client side can be configured here.

Directory is routin

Nuxt.js defines a set of automatic generation rules on top of vue-router, which is generated according to the directory structure of pages. For example, we have the following directory structure:

This directory contains a basic route (no parameters) and two dynamic routes (with parameters). Nuxt.js generates the following routing configuration table (which can be 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"}]

For the article-id route, the path has: id? Parameter, indicating that this is an optional route, and if you want to make it required, you must add the index.vue file in the article directory.

Look at the following example:

Due to the existence of files and folders with the same name, Nuxt.js will generate nested routes for us. The generated route structure is as follows. When we use it, we need to add tags to display the contents of the child view.

Routes: [{path: "/ article", component: _ f930b330, children: [{path: ", component: _ 1430822a, name:" article "}, {path:": id ", component: _ 339e8013, name:" article-id "}]}]

In addition, Nuxt.js can also set up dynamic nested routing, which can be found in Nuxt.js 's official documentation.

The above is all the contents of the article "sample Analysis of Vue.js Server rendering in Nuxt". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report