Home > Web Front-end > JS Tutorial > body text

Nuxt's Vue.js server-side rendering practice

小云云
Release: 2018-01-03 13:56:51
Original
2559 people have browsed it

Vue.js is one of the hottest front-end frameworks currently, and Nuxt.js is a server-side rendering framework launched for Vue.js. Through highly customized configurations and simple APIs, developers can quickly perform server-side rendering For the development of rendering projects, this article will give a brief introduction to the Nuxt.js framework. This article mainly introduces the detailed explanation of Vue.js server-side rendering practice based on Nuxt. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.

Server Side Rendering

Server Side Render (Server Side Render) is not a new concept. Before single page applications (SPA) became popular, The page is rendered on the server side and passed to the browser. When the user needs to access a new page, he needs to request the server again and return the new page.

In order to optimize the experience, developers began to choose to use JavaScript to complete the rendering process on the front end. By separating the front and back ends, the back end focused more on data, while the front end focused on processing and display. Through well-designed APIs And Ajax technology completes the interaction between the front and back ends, and frameworks such as jQuery, React.js, Vue.js, and Angular.js emerged as the times require.

These frameworks have brought great convenience to developers, but for some forums, information websites, or corporate official websites, they have some limitations on Search Engine Optimization (SEO) There are strong requirements, and front-end rendering technology cannot meet their needs. If you cannot output your own content through search engine searches, the value of the website will be greatly affected. To solve such problems, you still have to rely on server-side rendering.

This article will introduce Nuxt.js, Vue.js’s server-side rendering solution. 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. The vue-server-renderer officially provided by Vue.js can be used Performing server-side rendering requires additional workload, and the development experience still needs to be improved. After the launch of Nuxt.js, this problem was well solved.

Nuxt.js Introduction

Nuxt.js is a universal application framework based on Vue.js. Nuxt.js is preset to use Vue.js to develop server-side rendering. Various configurations required by the application, and static sites can be generated with one click. At the same time, the hot loading mechanism of Nuxt.js allows developers to develop websites very conveniently.

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

Easy to get started

Vue.js’s vue-cli tool allows us to easily initialize Vue.js projects using ready-made templates. The Nuxt.js team has provided us with a template for initializing the Nuxt.js project. After installing vue-cli, just enter


vue init nuxt/starter <projectName>
Copy after login
in the command line

To complete the creation of the project, then enter the project directory and execute the following command:


npm installnpm run dev
Copy after login

Nuxt.js will run using the 3000 port Service, enter http://localhost:3000 in the browser to see an original page with the Nuxt.js logo.

Project Directory

After completing a simple Hello World project, let’s further study Nuxt.js. After entering the Nuxt.js project, the project directory is as follows:

The following is a brief introduction to the functions 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 Nuxt.js for server-side rendering (see the next paragraph "Rendering Process of Nuxt.js"), router. The 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 various components in the project. Note that only files in this directory can be called components.

layouts/: Create a custom page layout. You can create a unified layout for global pages or an error page layout in this directory. If you need to render the routing pages in the pages directory in the layout, you need to add the <nuxt /> tag to the layout file.

middleware/: Place custom middleware, which will be called before loading the component.

pages/: In this directory, Nuxt.js will generate vue-router routes according to the structure of the directory, see below for details.

plugins/ :可以在这个目录中放置自定义插件,在根 Vue 对象实例化之前运行。例如,可以将项目中的埋点逻辑封装成一个插件,放置在这个目录中,并在 nuxt.config.js 中加载。

static/ :不使用 Webpack 构建的静态资源,会映射到根路径下,如 robots.txt

store/ :存放 Vuex 状态树。

nuxt.config.js :Nuxt.js 的配置文件,详见下文。

Nuxt.js 的渲染流程

Nuxt.js 通过一系列构建于 Vue.js 之上的方法进行服务端渲染,具体流程如下:

调用 nuxtServerInit 方法

当请求打入时,最先调用的即是 nuxtServerInit 方法,可以通过这个方法预先将服务器的数据保存,如已登录的用户信息等。另外,这个方法中也可以执行异步操作,并等待数据解析后返回。

Middleware

经过第一步后,请求会进入 Middleware 层,在该层中有三步操作:

读取 nuxt.config.js 中全局 middleware 字段的配置,并调用相应的中间件方法 匹配并加载与请求相对应的 layout 调用 layoutpage 的中间件方法

调用 validate 方法

在这一步可以对请求参数进行校验,或是对第一步中服务器下发的数据进行校验,如果校验失败,将抛出 404 页面。

调用 fetchasyncData 方法

这两个方法都会在组件加载之前被调用,它们的职责各有不同, asyncData 用来异步的进行组件数据的初始化工作,而 fetch 方法偏重于异步获取数据后修改 Vuex 中的状态。

我们在 Nuxt.js 的源码 util.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 after login

这个方法会在 asyncData 方法调用完毕后进行调用,可以看到,组件从 asyncData 方法中获取的数据会和组件原生的 data 方法获取的数据做一次合并,最终仍然会在 data 方法中返回,所以得出, asyncData 方法其实是原生 data 方法的扩展。

经过以上四步后,接下来就是渲染组件的工作了,整个过程可以用下图表示:

(图片来源:Nuxt.js 官网)

如上文所述,在 .nuxt 目录下,你可以找到 server.js 文件,这个文件封装了 Nuxt.js 在服务端渲染的逻辑,包括一个完整的 Promise 对象的链式调用,从而完成上面描述的整个服务端渲染的步骤。

Nuxt.js 的一些使用技巧

nuxt.config.js 的配置

nuxt.config.js 是 Nuxt.js 的配置文件,可以通过针对一系列参数的设置来完成 Nuxt.js 项目的配置,可以在Nuxt.js 官网 找到针对这个文件的说明,下面举例一些常用的配置:

head: 可以在这个配置项中配置全局的 head ,如定义网站的标题、 meta ,引入第三方的 CSS、JavaScript 文件等:


head: {
   title: &#39;百姓店铺&#39;,
   meta: [
      { charset: &#39;utf-8&#39; },
      { name: &#39;viewport&#39;, content: &#39;width=device-width, initial-scale=1&#39; },
      { name: &#39;applicable-device&#39;, content: &#39;pc,mobile&#39; },
   ],
   link: [
      { rel: &#39;stylesheet&#39;, type: &#39;text/css&#39;, href: &#39;https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css&#39;}
   ],
   script: [
      {src: &#39;https://code.jquery.com/jquery-3.1.1.min.js&#39;},
      {src: &#39;https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js&#39;}
   ]
 },
Copy after login

build: 这个配置项用来配置 Nuxt.js 项目的构建规则,即 Webpack 的构建配置,如通过 vendor 字段引入第三方模块,通过 plugin 字段配置 Webpack 插件,通过 loaders 字段自定义 Webpack 加载器等。通常我们会在 build 的 vendor 字段中引入 axios 模块,从而在项目中进行 HTTP 请求( axios 也是 Vue.js 官方推荐的 HTTP 请求框架)。


build: {
   vendor: [&#39;core-js&#39;, &#39;axios&#39;],
   loaders: [
     {
       test: /\.(scss|sass)$/,
       use: [{
         loader: "style-loader"
       }, {
         loader: "css-loader"
       }, {
         loader: "sass-loader"
       }]
     },
     {
       test: /\.(png|jpe?g|gif|svg)$/,
       loader: &#39;url-loader&#39;,
       query: {
         limit: 1000,
         name: &#39;img/[name].[hash:7].[ext]&#39;
       }
     },
     {
       test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
       loader: &#39;url-loader&#39;,
       query: {
         limit: 1000,
         name: &#39;fonts/[name].[hash:7].[ext]&#39;
       }
     }
   ]
 }
Copy after login

css: 在这个配置项中,引入全局的 CSS 文件,之后每个页面都会被引入。

router: 可以在此配置路由的基本规则,以及进行中间件的配置。例如,你可以创建一个用来获取 User-Agent 的中间件,并在此加载。

loading: Nuxt.js 提供了一套页面内加载进度指示组件,可以在此配置颜色,禁用,或是配置自定义的加载组件。

env: 可以在此配置用来在服务端和客户端共享的全局变量。

目录即路由

Nuxt.js 在 vue-router 之上定义了一套自动化的生成规则,即依据 pages 的目录结构生成。例如,我们有以下目录结构:

这个目录下含有一个基础路由(无参数)以及两个动态路由(带参数),Nuxt.js 会生成如下的路由配置表(可以在 .nuxt 目录下的 router.js 文件中找到):


routes: [
  {
    path: "/",
    component: _abe13a78,
    name: "index"
  },
  {
    path: "/article/:id?",
    component: _48f202f2,
    name: "article-id"
  },
  {
    path: "/:page",
    component: _5ccbb43a,
    name: "page"
  }
]
Copy after login

对于 article-id 这个路由,路径中带有 :id? 参数,表明这是一个可选的路由,如果要将其设为必选,则必须在 article 的目录下添加 index.vue 文件。

再看下面一个例子:

由于有同名文件和文件夹的存在,Nuxt.js 会为我们生成嵌套路由,生成的路由结构如下,在使用时,需要增加 <nuxt-child /> 标签来显示子视图的内容。


routes: [
  {
    path: "/article",
    component: _f930b330,
    children: [
      {
        path: "",
        component: _1430822a,
        name: "article"
      },
      {
        path: ":id",
        component: _339e8013,
        name: "article-id"
      }
    ]
  }
]
Copy after login

此外,Nuxt.js 还可以设置动态嵌套路由,具体可参见Nuxt.js 的官方文档。

总结

Nuxt.js 尽管是一个非常年轻的框架,目前也有很多待改进的问题,但它的出现为 Vue.js 开发者搭建服务端渲染项目提供了巨大的便利,期待 Nuxt.js 1.0 版本发布后,能给我们带来更多实用的新功能。

相关推荐:

详解React服务端渲染实例

webpack+react+nodejs服务端渲染_html/css_WEB-ITnose

Diy页面服务端渲染解决方案_html/css_WEB-ITnose

The above is the detailed content of Nuxt's Vue.js server-side rendering practice. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template