Server-side rendering and Nuxt.js

This article is reproduced in: Ape 2048 Website ➪ https://www.mk2048.com/blog/blog.php?id=hca02aakaa

From the perspective of the development history of front-end server-side rendering

Some time ago to see a question on almost know, that's why now become popular server side rendering of html. Finishing up some online comments, combined with their own ideas, sorting out some history of front-end development.

As early as 1989, the birth of HTML is an academic physicist in order to facilitate sharing of documents created, this is the front end of the starting time. Later, CSS and Javascript to join the front ranks, used to render the page style and page processing logic dynamic efficiency, front-end establishment of The Three Musketeers. The beginning of the front-end programmers, in fact, do write Cut chart styles (CSS) and page effects do (JS) and so on the basis of all, at the bottom programmers despise chain.
With the development of the Internet and advances in technology, static pages already can not meet demand, to produce dynamic data according to the logic of the page, then, will usher in the web1.0 era PHP, JSP as the representative. At this point the server rendering, is to "document" as the core idea. Server-side logic is the HTML, CSS and JS as a static document, to "document" in terms of the distinction between "instruction" and "data" does not exist, everything is data. So we can see the server rendering, GET is requesting a file, while many other server-side framework web 1.0 era is one of the components most basic document templates, such as asp, JSP and the like, the core design philosophy is to put HTML file placeholder after replacing the operator then fall returned by the service to the actual data of the logic. Many small and medium sized projects, regardless of front-end back-end, we are all web development engineers, according to current theory called full-stack engineer. In the present situation, such a model is a lot of problems, take jsp example, fully coupled dynamic resource and static resources, server pressure, but once the situation appears, comes to an end with the front and back, the user experience is poor; jsp must run support java web server, the performance not to mention up; if jsp in a lot of content, the page is slow to respond ......
in 1998, IE5.0 introduction of XMLHttpRequest technology to achieve an asynchronous call to the server function, in 2005, Google in it is well-known interactive applications using ajax asynchronous communication, web 2.0 revolution led to the front. XMLHttpRequest released after W3C standards, ajax outbreak provide a technical basis for the later.
In 2006, JQuery library publishing tool, once born with characteristics of its simple turning of browser compatibility and the ability to solve swept the globe.
In 2010, Backbone birth, RequireJS first version, modular development of the front end of the era officially arrived. Then, with the rise of the front end of MVC, SPA (Single Page Application single-page application) started to become a trend of the project development, before and after the end of the division of labor is very clear. Front-end work in the browser, the back-end work on the server side. A clear division of labor, allows parallel development, simulation test data is not difficult, the front end can be local development. At this time, the front end of the separation movement between the major companies in the rise, the front end of his own, independent development. Front-end programmers the opportunity to stand up.
But this time, a lot of this should not be made SPA also made a SPA. However, there are problems SPA applications, such as SEO, such as the first screen loading speed, which makes front-end developers to optimize worry white head.
With the rise of Node.js, Javascript began to have the ability to run on the server side, which means that there is a new R & D model: Front-end UI layer processing logic to show the browser layer, Back-end UI layer handles the routing, template, data acquisition, cookie and other. By Node, Web Server layer of JavaScript code, which means that the front and rear part of the code can be reused, SEO needs to be synchronized scenes rendered on the server side, due to the asynchronous request performance problems caused by too much can also be alleviated by the server. Less than the former model, almost all perfect solution out of this mode.
Before and after the revolution is not the greatest idea of ​​the nature of the Web 2.0 era end of the separation, but the Web page as a stand-alone application (app). Before and after the end of the separation is to achieve the inevitable result of this new architecture. For program instructions and data are separated. After the page is not rendering HTTP GET to get, but a composition of the html and Javascript app, this app browser-virtual machine. Loading and display data after the logical operation app starts. What app called on tradition? Called Client, which is the front end. So the front and rear ends so isolated, the browser into the operating environment of the app, the back-end degenerate become pure business logic and data interface. Javascript is no longer to write the page to add special effects tricks, but decent and write desktop applications like engineering. So we see the front-end engineering, compilation (translation), various MVC / MVVM framework, rely on tools, and so on.

Why use server-side rendering?

Using server-side rendering, the main problem, in fact, in order to solve SEO problems. If the SPA applications have good SEO, server side rendering would not be too much trouble. Of course, server-side rendering can solve the problem first screen loading speed is one of the reasons. So, what SEO is it?
SEO (Search Engine Optimization), search engine optimization. Such as Google, Baidu needs to crawl the site information you post to the natural order, it is carried out by crawlers.
Look at two pieces of code:

Prior to the above is the code written much earlier reptiles Nuggets two articles (written by a little low), probably the idea is to send http requests using superagent, the entire page (document object) to climb down, including the head, body and so on, then parsed by cheerio, then fetch page node elements and key information. You may think that this simple, I request to all the information on the page and then inserted into the dom elements via ajax. Note that the reptile crawled the page and does not send ajax request is an initialization of pure static pages, if you are using a spa applications, it may be a body in addition to the node id of the app, nothing. So, we need to make the page has been rendered completed on the server side to the client's time is already a static html document data having information. Of course, now there are SEO optimization scheme for SPA application, this is not within the scope of this article.
The following lists the total number of server-rendered pros and cons:

advantage

  • Conducive to SEO.
  • The first screen fast loading speed. Because SPA cited the need to get all the resources in the first screen, and server-side rendering directly took Finished products out on the line.
  • Without taking up client resources. Templates to the server to complete the analytical work, the client uses less resources, especially for the mobile terminal can also be more energy-efficient.

Shortcoming

  • Tying up server resources. Html template parsing the server side, if the request is more, will cause the server to access certain pressure. And if it is front-end rendering, it is to share these pressures to the front end.
  • Before and after the end of the separation is not conducive.

SSR VIEW

Universal (also known as isomorphic) of JavaScript JavaScript community has become a very common term. JavaScript can be used to describe a common implementation of the client side, you can also be performed on the server side Javascript code. In the official document VUE is so described:

Vue.js is a framework for building client applications. By default, Vue assembly may be output in the browser, and operation for generating a DOM DOM. However, it is also possible to render the same component as the server-side HTML string, send them directly to the browser, and finally static marks "hybrid" application is fully interactive on the client.

The first phrase is easy to understand, that you can server (back-end) environment using vue.js to build components and pages, then the rendered static html string to the client display. The last part of the sentence is not fluent feeling, the English version is this:

“Finally "hydrate" the static markup into a fully interactive app on the client.”

Probably meant to say, after the application to the client, due to some static markup, the client will have the same interaction (MVVM is a two-way data binding).

This construction procedure diagram given in the official website can be seen, for client applications and server applications, we have to use webpack packaging - servers need "server bundle" is then used server-side rendering (SSR), and "Customer end bundle "will be sent to the browser, for mixing static marks. In this paper, but more in-depth Vue SSR content source raw, Vue official recommended a good community project Nuxt.js, it provides a very good experience for the development of server-side rendering Vue, we will mainly discuss it.

Nuxt.js

What Nuxt.js that?

JavaScript programs to build server-side rendered somewhat boring, before you start coding, you need a lot of basic configuration. Therefore, Nuxt.js solve vue.js server-side rendering problems arise. Nuxt.js is a generic application framework Vue.js based. Various pre-configuration required for server-side rendering, such as asynchronous data, middleware, routing, just follow the rules of which you can easily achieve SSR. . It is like Angular Universal is to the Angular, Next.js is to the React. By abstracting organization of client / server infrastructure, Nuxt.js main concern is the application UI rendering.

What do Nuxt.js

  • No longer need to worry about routing division, just create .vue file in accordance with the corresponding folder hierarchy on the line
  • Irrespective of data transmission problems, nuxt asynchronously request data before output template (need to introduce axios library), but to further package vuex
  • Built webpack, eliminating the step of configuring WebPACK, nuxt will be packaged in accordance with the corresponding configuration file

Nuxt.js installation and operation

In the case of mounting vue-cli quickly generates a command nuxt item follows:

$ vue init nuxt-community/starter-template <project-name>

After entering the project directory

$ npm install

Then start the project

$ npm run dev

Such projects can be running in http://localhost:3000the

Nuxt.js practical introduction

Not detail here and some uses of the API nuxt.js, directly Tell me what network tutorial: https://zh.nuxtjs.org/guide .
I made a simple demo nuxt.js the (very simple), Github address , here's some of my own experience, compared to spa applications, to talk about this framework.

1. Nuxt.js directory structure

nuxt is to use a template to create a vue-cli, compared to conventional vue template, they have a very important point: convenience. nuxt.js also been required for various projects webpack we take care of the configuration, out of the box, basically do not need to make any changes. And even if you need to customize some configuration, it is also very simple to modify. Let's put it in the directory structure and the SPA be used as a comparison.

As can be seen from the figure, nuxt seems a lot of content to the src folder to put outside, less a number of documents, more than a few files have not seen the clip. These folders use for each.

  • layouts for placing the page layout.
  • middleware for placing some of middleware, we can refer to these pages middleware components, which will first perform a logical page during execution logic.
  • pages is to place all of our friends page components, however, it is different and spa applications, nuxt where the page will generate a folder structure corresponding routing, based on an analogy file and directory structure beneath my page folder as follows
pages/
--| _slug/
-----| comments.vue
-----| index.vue
--| users/
-----| _id.vue
--| index.vue

Nuxt.js generate the corresponding routing table configured to:

router: {
  routes: [
    {
      name: 'index',
      path: '/',
      component: 'pages/index.vue'
    },
    {
      name: 'users-id',
      path: '/users/:id?',
      component: 'pages/users/_id.vue'
    },
    {
      name: 'slug',
      path: '/:slug',
      component: 'pages/_slug/index.vue'
    },
    {
      name: 'slug-comments',
      path: '/:slug/comments',
      component: 'pages/_slug/comments.vue'
    }
  ]
}
  • plugins centrally located some plug-ins, such as axios and so on.
  • It is defined centrally store state tree. nuxt.js has integrated vuex, there is only a need to define index.js, and then exposed to a Vuex.Store Foreign instance can be. However, after stepping pit, SPA state tree and here's a little different, and so will say this.

2. Nuxt.js page components

From the comparison of FIGS. Nuxt.js and the SPA .vue ,, single-page document instance attributes in addition to conventional general .vue single-page document (such as data, methods, props, etc.), Nuxt.js also provides many convenient another interesting property, which is one of the biggest feature Nuxt.js.

  1. Throughout the implementation of internal processes nuxt, the first after the status of the management actionsof nuxtServerInit function, we'll deal with this.
  2. Then will go through middlewarein the middleware functions, this time, there is no data access and page rendering, so we can perform some logic before entering the route middleware functions, such as user rights judge.
  3. After the start of the page data acquisition, and data results asyncData essentially the same, we can directly call the server interface, such as the grounds axios send http request to obtain the original data page you want, and then return to go out in the form of the object, at this time, Vue object also no instantiation, so there can not be invoked to asyncData this.
  4. fetch status tree was mainly used as a filler (Store) data.
  5. After all these done, began to instantiate an object Vue, where logic and single-page application is the same, after assembled the entire page application, nuxt.js this application will return to the front. Note that this is not a simple return to the page, but the application. At this point some properties of partial page spa applications, such as data monitor two-way binding.
  6. When the page came to the front, began to mount the implementation of the relevant logic.
    In addition to the execution flow of the application, and then look at page rendering module.
  • headYou can customize the header information part of the current page, such as title, meta and the like. Of course, if desired head may define a global nuxt.config.jsconfiguration.
  • layoutSection can customize the page layout, a lot of page public static head, tail section can demand a uniform definition references.
  • scrollToTopTop of the page when scrolling a page for a jump.
  • transitionAnimated transitions between pages for jump.

3. Vuex state tree

Do down the entire demo, there impressed me most is the state tree, use it and SPA still have some differences.
At that time I need to complete requirements that store user information, and you can use it on any page, if not non-login page to obtain user information, jump back to the login page .
At first, my design idea is, after the user logs in successfully, the user interface to obtain call back all of the information, and there is a store. Flowchart is as follows:

According to the case SPA application, store the data in the page should be components are shared. However, once the page jump Nuxt found, the entire tree will be reset Vuex state, able to save the original user information as well. It can be speculated that the page is in a different routing of separate application, they do not share data in the state.
Then I thought of the local session storage localStorage, as long as the original process was changed from a logical store can be accessed from the logic of localStorage. This approach is feasible, but this way, Vuex not feel stronger sense of presence (the matter on to something), and the like would not be able to control the expired logical session with the server layer.
It was discovered that the server-side rendering vuex of action provides a method: nuxtServerInit . Nuxt.js context object to call it when the page will be passed as the second argument to it, you can get the context object req request object, then there is such a kind of logic. I can store user information in the server session, and then through req.session.user to access the user currently logged on. The user login information to the client of the status tree, as follows:

actions: {
  nuxtServerInit ({ commit }, { req }) {
    if (req.session.user) {
      commit('user', req.session.user)
    }
  }
}

Such mating middleware middleware, the user can be completed and session control information acquisition process is as follows:

Other related to 4. Nuxt.js

Other content also relates, in fact, take a look at the official website tutorial, take a look at an example of net official can get, the tutorial is very easy to understand.

to sum up

Use Vue, React and other server rendering, not to go before the old template rendering. It has crossed history, towards the development of better. And Nuxt.js, is still a very young framework (version 0.10.7 is now the official website), currently there are many problems to be improved, but its presence is Vue.js developers to build server-side rendering program provides great convenience . I heard Nuxt.js 2.0 is coming, look after release, can bring us more useful new features.

Guess you like

Origin www.cnblogs.com/dssx/p/11783941.html