nuxt.js的核心代码

by Krutie Patel

通过克鲁蒂·帕特尔(Krutie Patel)

Nuxt.js中的通用应用程序代码结构 (Universal application code structure in Nuxt.js)

Nuxt.js中的源代码结构的简要摘要 (A brief summary of source code structure in Nuxt.js)

Are you new to the Nuxt.js framework and totally overwhelmed by the number of folders it comes with? Are you also surprised that most of them are empty with just the readme file in them? Well, that’s where I was little over a year ago. Since then, I’ve always wanted to learn and document the magic that each folder brought into the Nuxt project.

您是Nuxt.js框架的新手,并且对它附带的文件夹数量感到不知所措吗? 您是否也对其中大多数文件都为空,而其中仅包含自述文件感到惊讶? 好吧,那是我一年多以前的地方。 从那时起,我一直想学习并记录每个文件夹带入Nuxt项目的魔力。

And now, after implementing a few projects with this framework, I have documented my understanding of how these folders work together to bring the server-rendered Vue application to life.

现在,在使用此框架实施了一些项目之后,我记录了对这些文件夹如何协同工作以使服务器渲染的Vue应用程序栩栩如生的理解。

The diagram above is based on Vue SSR guide, and extended with Nuxt.js in mind. At a glance, you see different folders in Your universal application code section, and how the code is then, packaged by Nuxt and bundled by Webpack.

上图基于Vue SSR指南 ,并在扩展时考虑了Nuxt.js。 一目了然,您会在“通用应用程序代码”部分中看到不同的文件夹,以及如何通过Nuxt打包并通过Webpack打包代码。

This article is neither tutorial nor complete guide to Nuxt SSR. It rather shows what goes into universal application.

本文既不是教程,也不是Nuxt SSR的完整指南。 而是显示了通用应用程序中的内容。

Although you see modules, serverMiddleware, and plugins at the top of the diagram, let’s start with Store first.

尽管您在图的顶部看到模块,serverMiddleware和插件,但让我们先从Store开始。

Vuex商店(/商店) (Vuex Store (/store))

Nuxt comes pre-packaged with Vuex, but it’s not activated unless you make a Vuex store in the /store directory and create the store.

Nuxt预先与Vuex打包在一起,但是除非您在/ store目录中创建Vuex商店并创建商店,否则它不会被激活。

This is very special directory for any data-driven project. This is where you can create a data-store, as well as define the nuxtServerInit action. This happens to be the very first lifecycle hook as well!

对于任何数据驱动的项目,这都是非常特殊的目录。 在这里您可以创建数据存储,以及定义nuxtServerInit操作。 这恰好也是第一个生命周期挂钩!

const createStore = () => {  return new Vuex.Store({     ...  })}

When the user initially accesses your application, this helps fill/update the store. It also maintains the state of your data throughout the application.

当用户最初访问您的应用程序时,这有助于填充/更新商店。 它还可以维护整个应用程序中数据的状态。

路由中间件(/中间件) (Route Middleware (/middleware))

There are three different kinds of route middleware available in Nuxt. They are all defined in one central location — in the /middleware directory.

Nuxt提供了三种不同的路由中间件。 它们都在/ middleware目录的一个中央位置定义。

From here, you can use them in the following ways:

从这里,您可以通过以下方式使用它们:

  • Global middleware — (entry via Nuxt config and affects all routes)全局中间件-(通过Nuxt配置进入并影响所有路由)
// nuxt.config.js
export default {  router: {    middleware: 'authenticated'  },}
  • Layout middleware (entry via layouts and affects group of matching routes, i.e. certain pages only to be viewed/accessed by authenticated users)布局中间件(通过布局进入并影响一组匹配的路线,即某些页面仅由经过身份验证的用户查看/访问)
// layouts/default.vue
export default {  middleware: 'authenticated-basic-plan-user'}
  • Page middleware (entry via page component and affects single route)页面中间件(通过页面组件进入并影响单个路由)
// pages/index.vue
export default {   middleware: 'subscribed'}

The middleware above are dealt in this exact order — meaning, their priorities are non-negotiable. So you must think through and plan your application carefully to get the most use out of them.

上面的中间件是按照确切的顺序处理的-这意味着它们的优先级是不可协商的。 因此,您必须仔细考虑并计划应用程序,以充分利用它们。

Vue组件 (Vue Components)

There are three directories where .vue files are created in a Nuxt project.

在Nuxt项目中创建三个目录的.vue文件。

1.页面组件 (/页) (1. Page components ? (/pages))

This is the most important directory of all that houses application views and routes. Vue.js components created here are directly converted into application routes.

这是存放应用程序视图和路由的所有目录中最重要的目录。 此处创建的Vue.js组件直接转换为应用程序路由。

The real power of page components lies in dynamic routes. You can use them to generate SEO friendly and data-oriented URLs. Dynamic routes are generated based on your directory structure under /pages.

页面组件的真正力量在于动态路由。 您可以使用它们来生成SEO友好和面向数据的URL。 动态路由是根据/ pages下的目录结构生成的

In addition, Nuxt adds three special methods on page components which aren’t available anywhere else. They are validate(), asyncData() & fetch().

另外,Nuxt在页面组件上添加了三种特殊方法,这些方法在其他任何地方都无法使用。 它们是validate()asyncData()fetch()

// pages/index.vue
export default {
validate() {     // validates dynamic URL parameters     // verifies the availability of the data  },   asyncData() {     // sets component data  },
fetch() {    // doesn't set component data, but     // fetches further contextual data  }
}

2.布局组件(/布局) (2. Layout components (/layouts))

Layout components power the structural aspects of your application. Common components found on all pages are created here (like main menu, secondary menu, header, footer, etc.). They’re located in the /layouts directory.

布局组件为应用程序的结构方面提供了动力。 在此处创建所有页面上的通用组件(例如主菜单,辅助菜单,页眉,页脚等)。 它们位于/ layouts目录中。

You can be as creative as you want here, after all they are Vue.js components. Don’t forget to add <nuxt/> in the main content area of the layout.

它们毕竟是Vue.js组件,因此您可以在这里发挥自己的创造力。 不要忘记在布局的主要内容区域添加<nux t />。

<template>  &lt;div>     <nuxt/>  </div></template>

Incorporate route-middleware and store data-state with the layout component to build perfect who-sees-what features for any number of user-types with varied scenarios. You can achieve a bit more than just with a custom user interface.

路由中间件与布局组件相结合存储数据状态 ,以针对各种场景下的任意数量的用户类型构建完善的“ 看谁看”功能。 您不仅可以通过自定义用户界面实现更多目标。

3. Vue.js组件(/ components) (3. Vue.js components (/components))

These are regular, but versatile Vue components. They are created under the /components directory. They are not supercharged with special methods like Page components.

这些是常规但通用的Vue组件。 它们在/ components目录下创建。 它们不会使用诸如Page组件之类的特殊方法来增强。

But they allow you to structure and organize your business logic. They also hide heavy markup from page and layout components. This makes your codebase more manageable.

但是它们允许您构造和组织业务逻辑。 它们还会在页面布局组件中隐藏沉重的标记。 这使您的代码库更易于管理。

Now look closely — can you see the partial folder structure in this Nuxt lifecycle diagram?Hint: Store (nuxtServerInit), Route Middleware and Page components (validate, asyncData & fetch methods)

现在仔细观察-您可以在此Nuxt生命周期图中看到部分文件夹结构吗? 提示:存储(nuxtServerInit),路由中间件和页面组件(验证,asyncData和获取方法)

资产 (Assets)

Webpacked资产(/资产) (Webpacked assets (/assets))

Assets such as JavaScript files, custom fonts, and CSS files are processed by Webpack using specific loaders (css-loader, file-loader, url-loader etc) depending upon file types. For example, if you write your CSS in .scss or .less format then Webpack will process these files using a specific loader and output compiled .css file that can be used by the browser.

Webpack使用特定的加载器(css​​-loader,file-loader,url-loader等)来处理JavaScript文件,自定义字体和CSS文件之类的资产,具体取决于文件类型。 例如,如果您以.scss.less格式编写CSS,则Webpack将使用特定的加载器处理这些文件,并输出浏览器可以使用的已编译.css文件。

You can even customize your nuxt.config.js to instruct Webpack to minify and optimize images in the assets folder as a part of your build process. After Webpack processes the files, it attaches hash-code — for example, index.4258e3668a44556dd767.js — to the processed items which helps in long-term caching of dynamic assets and cache-busting.

您甚至可以自定义nuxt.config.js,以指示Webpack在构建过程中缩小和优化资产文件夹中的图像。 Webpack处理文件后,它将哈希码( 例如index.4258e3668a44556dd767.js)附加到已处理的项目,这有助于长期缓存动态资产和清除缓存。

静态资产(/静态) (Static assets (/static))

For the assets that will not change, you can safely put them in the static folder. Webpack ignores the static folder and will not process anything in there.

对于不会更改的资产,您可以安全地将它们放在静态文件夹中。 Webpack会忽略静态文件夹,并且不会在其中处理任何内容。

模块,服务器中间件和插件 (Modules, serverMiddleware and plugins)

They are all defined (by their path) in Nuxt configuration. They are accessible globally within the Nuxt application.

它们都是在Nuxt配置中定义的(通过它们的路径)。 在Nuxt应用程序中可以全局访问它们。

模块(/模块) (Modules (/modules))

A fresh Nuxt application is pre-packaged with Vue, Vue Router, Vuex, Vue Server Rendered and Vue Meta by default.

默认情况下,新的Nuxt应用程序已预先打包有Vue,Vue路由器,Vuex,Vue服务器渲染和Vue Meta。

But you may wonder, what about features like Sitemap, Google Analytics, Progressive Web Apps, or more? If you’re thinking of using modules, then yes, you are right, this is where the power of Nuxt modules come into play.

但是您可能想知道,Sitemap,Google Analytics(分析),Progressive Web Apps或其他功能如何? 如果您正在考虑使用模块,那么是的,您是对的,这正是Nuxt模块发挥作用的地方。

serverMiddleware(即/ api) (serverMiddleware (i.e. /api))

serverMiddleware can be considered an extension point for your application. They are special because they have access to the underlying instance of the connect framework.

serverMiddleware可以被视为您的应用程序的扩展点。 它们之所以特别,是因为它们可以访问连接框架的基础实例。

Since Nuxt uses connect to deliver the application, it allows custom functions to be hooked into the underlying request pipeline as middleware.

由于Nuxt使用connect来交付应用程序,因此它允许将自定义函数作为中间件挂接到基础请求管道中。

You can use serverMiddleware to:

您可以使用serverMiddleware来:

  • Create an API endpoint to connect to external applications.创建一个API端点以连接到外部应用程序。
  • Create an API endpoint to send email to users from your Nuxt application.创建一个API端点,以从您的Nuxt应用程序向用户发送电子邮件。
  • Access and modify the request in any way, even before it reaches Nuxt.甚至可以在到达Nuxt之前以任何方式访问和修改请求。

Note that you don’t have any pre-populated empty folders for serverMiddleware and modules. You create them when needed.

请注意,对于serverMiddleware和模块,您没有任何预填充的空文件夹。 您可以在需要时创建它们。

插件(/插件) (Plugins (/plugins))

You can make your existing Vue mixins, filters, or directives work harder just by converting them into Nuxt plugins. You place them in the /plugins directory that comes with a fresh Nuxt installation.

您只需将现有的Vue mixin,过滤器或指令转换为Nuxt插件,就可以使其工作更加困难。 您可以将它们放在新安装的Nuxt随附的/ plugins目录中。

But most of the time, you will end up adding external packages or Vue libraries as Nuxt plugins. You incorporate them in Nuxt by simply using Vue.use() syntax. Some of the staple plugins I always end up using in my Nuxt implementation are Vue Bootstrap, form validation, font-awesome icon-set and axios.

但是大多数时候,您最终会添加外部软件包或Vue库作为Nuxt插件。 您只需使用Vue.use()语法将它们合并到Nuxt中。 我经常在Nuxt实现中最终使用的一些主要插件是Vue Bootstrap,表单验证,超棒的图标集和axios。

That’s not the end of plugins. You can write custom plugins and add them in the application root. They are available globally in your Nuxt application. This is my personal favorite way of adding custom GreenSock or Scroll-Magic transitions into the project, and using them in the Vue (/components) and Page (/pages) components.

插件还没有结束。 您可以编写自定义插件并将其添加到应用程序根目录中。 它们在您的Nuxt应用程序中全局可用。 这是我个人最喜欢的将自定义GreenSock或Scroll-Magic过渡添加到项目中,并在Vue (/组件)和Page (/ pages)组件中使用它们的方式。

模块,服务器中间件和插件的高级概述 (High-level overview of modules, serverMiddleware and plugins)

包装,捆绑和交付 (Package, bundle and deliver)

Once you have the desired features in place, you build your application using npm run build. Nuxt packages your application.

具备所需功能后,即可使用npm run build来构建应用程序 Nuxt打包您的应用程序。

As shown in the diagram below, index.js is the main entry point, which imports app.js.

如下图所示, index.js是导入app.js的主要入口点。

App.js defines the root Vue instance. If you look closely in .nuxt/App.js, it’s nothing but a Vue component.

App.js定义了根Vue实例。 如果您仔细查看.nu​​xt / App.js ,那么它就是Vue组件。

Once this root Vue instance is defined, client entry (client.js) creates a new instance based on it and mounts it to the DOM element. End-users see a fresh instance of an app in their browsers. While server entry (server.js) creates a new app instance for each request.

定义此根Vue实例后,客户端条目( client.js )将基于该实例创建一个新实例,并将其安装到DOM元素。 最终用户会在浏览器中看到一个应用程序的新实例。 服务器条目( server.js )为每个请求创建一个新的应用程序实例。

And finally, Webpack bundles your app so that the code runs on both the client and server side. The server bundle renders the server side, and the client bundle hydrates static HTML markup in the browser. It turns it into a dynamic DOM that can react to client-side data changes.

最后,Webpack捆绑了您的应用程序,以使代码在客户端和服务器端均可运行。 服务器捆绑包呈现服务器端,而客户端捆绑包在浏览器中合并静态HTML标记。 它将其转变为可以对客户端数据更改做出React的动态DOM。

Nuxt does this all out of the box for us, so you don’t have to write this setup manually. Lots of complexity goes into the last two steps — packaging and bundling. But Nuxt hides all of it from you. You can concentrate on the application code that eventually delivers the final application.

Nuxt为我们提供了开箱即用的功能,因此您无需手动编写此设置。 最后两个步骤涉及很多复杂性-包装和捆绑。 但是Nuxt对您隐藏了所有这些内容。 您可以集中精力于最终交付最终应用程序的应用程序代码。

结论 (Conclusion)

I hope this higher level overview of the application code structure takes you one step further in your learning journey of the Nuxt framework.

我希望对应用程序代码结构的更高层次的概述可以使您在学习Nuxt框架的过程中迈出新一步。

This is one of many alternate perspectives to help you make sense of how everything fits together in a Nuxt application.

这是许多替代观点之一,可以帮助您理解Nuxt应用程序中的所有内容如何组合在一起。

For me personally, this little exercise helps me:

对我个人而言,这种小运动可以帮助我:

  • map out the requirements of the project against out-of-the-box Nuxt features根据开箱即用的Nuxt功能绘制项目需求
  • list relevant community modules & plugins that are already available, and列出已经可用的相关社区模块和插件,以及
  • pick out the remaining/complex bits that require custom development.选择需要定制开发的其余/复杂位。

图表链接与上面使用的图表的高分辨率版本 (Diagrams links with high-res versions of the diagrams used above)

  1. Nuxt Js lifecycle hooks

    Nuxt Js生命周期挂钩

  2. Understanding modules, serverMiddleware and plugins

    了解模块,服务器中间件和插件

  3. Universal application code in Nuxt.js

    Nuxt.js中的通用应用程序代码

Feel free to reach out with comments, feedback or even a suggestion for new diagram ideas you would like to see — in the comment section below.

欢迎在下面的评论部分中与您想看到的新图表想法相关的评论,反馈甚至建议。

If you’re new to Nuxt, then you may want to check out my earlier article on this topic “Why Nuxt Js is the perfect framework for your landing page? That will give you deeper insight in the nitty-gritty of developing applications with Nuxt.

如果您是Nuxt的新手,那么您可能想看看我以前关于此主题的文章“ 为什么Nuxt Js是您的目标网页的理想框架? 这将使您更深入地了解使用Nuxt开发应用程序的本质。

你是纳克斯吗? (Are you Nuxt yet?)

When @_achopin asked at the @vuejsamsterdam, “Are you Nuxt?” I thought, hey… I am Nuxt.

当@_achopin要求在@vuejsamsterdam ,“你Nuxt?” 我以为,嘿...我是Nuxt。

And I created these Nuxt stickers — professionally printed by Moo Printing and ready to be shipped if you’re interested. Alternatively, you can order them on RedBubble as well.

我创建了这些Nuxt贴纸 -由Moo Printing专业印刷,如果您有兴趣可以随时发货。 另外,您也可以在RedBubble上订购它们。

翻译自: https://www.freecodecamp.org/news/universal-application-code-structure-in-nuxt-js-4cd014cc0baa/

nuxt.js的核心代码

nuxt.js的核心代码_Nuxt.js中的通用应用程序代码结构相关推荐

  1. java代码套路,开发中比较容易理解的代码套路

    前言 今天给大家纯手工整理一下本人在开发中认为比较有用的代码思想套路,欢迎大家可以与我一同讨论 链式编程 所谓链式编程即是函数调用后返回对象本身 var calculator = { total:0, ...

  2. python有趣代码-wtfPython―Python中一组有趣微妙的代码【收藏】

    wtfPython是github上的一个项目,作者收集了一些奇妙的Python代码片段,这些代码的输出结果会和我们想象中的不太一样: 通过探寻产生这种结果的内部原因,可以让我们对Python里的一些细 ...

  3. 为什么单片机的代码在Flash中运行,单片机的代码运行位置跟电脑有什么不同?

    1. 单片机与电脑,在代码运行空间的区别 单片机与 电脑/Linux嵌入式 在代码运行的空间上不同.大多数单片机,代码都是在Flash中运行的.而电脑/linux嵌入式,是将代码从存储介质(可能是硬盘 ...

  4. python回声程序echo 一行代码_echo speex中的回声消除程序,可以直接在vs下运 效果还 有测试语料 Audio program 238万源代码下载- www.pudn.com...

    文件名称: echo下载 收藏√  [ 5  4  3  2  1 ] 开发工具: Visual C++ 文件大小: 5481 KB 上传时间: 2014-08-07 下载次数: 10 提 供 者: ...

  5. python函数和代码复用思维导图_Python语言程序---代码复用与函数递归(二)

    Python语言程序---代码复用与函数递归(二) 函数递归 在函数定义中,调用函数自身的方式就是递归. 递归并不是程序设计的专有名词,在数学中也广泛存在.例如:n!.在n!中,我们定义当n=0时,n ...

  6. 投票功能+代码+java_JSP实现的简单Web投票程序代码

    这篇文章主要介绍了JSP实现的简单Web投票程序代码,较为详细的分析了JSP实现投票功能的具体步骤与相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下 本文实例讲述了JSP实现的简单Web投票程序. ...

  7. html ajax实现分页代码,用jQuery中的ajax分页实现代码

    功能简介:主要功能就是分页显示数据了,可在配置文件中配置每页要显示的页码,可以做多条件联合查询,这里只是做一个简单的查询.欢迎拍砖,有问题的还望大虾们斧正哈.看看这个效果图,无刷新的噢!! 具体实现请 ...

  8. c语言编程等边三角形代码,C语言中 正 倒等边三角形的代码

    满意答案 lgznqjfqy 2019.03.07 采纳率:43%    等级:10 已帮助:418人 你这个输出的应该是一个菱形吧? 代码如下: #include #include int main ...

  9. python简单程序代码-有那些用python修改python程序代码的简单方法?

    python源代码是用C写的. 想改源库用python实现好像不太现实. 按你的要求,用C来extend的话很简单. ============下面是扩展库的代码=========== 用C来exten ...

最新文章

  1. ATS中的动态回源插件stale-while-revalidate调研
  2. CentOS 6.3 64bit上测试ATS 5.3.0中的正则刷新插件regex_revalidate
  3. mysql 30天销量_mysql查询今天,昨天,近7天,近30天,本月,上一月数据方法
  4. 检查压缩包是否损坏_修复损坏的gzip压缩文件之原理篇
  5. vector机器人 HOW TO MEET VECTOR 如何满足向量
  6. WireShark过滤器选项
  7. java中部的分页实现(二)
  8. 使用VLC转码,在HTML5页面播放实时监控
  9. 计算机目标导学方法,计算机教学计划
  10. 直接在安装了redis的Linux机器上操作redis数据存储类型--List类型
  11. Leetcode 5067.统计只含单一字母的子串
  12. 维修电工技师、高级技师技能实训考核装置
  13. 计算机网络原理中子网掩码,计算机网络应用 子网掩码计算器(SubNetMaskCalc)
  14. 安装mysql电脑开机蓝屏_电脑开机蓝屏怎么解决。
  15. c语言程序转python_c语言转python
  16. 国科大在线android版app,国科大心理app
  17. NVIDIA GeForce GTX 1050 Ti性能如何
  18. SIP/VoIP之常见的语音问题
  19. C语言关于有符号和无符号变量相互赋值的探讨
  20. 【Android 使用tinyalsa测试音频】

热门文章

  1. python基础教程(十一)
  2. 在双系统(Windows与Ubuntu)下删除Ubuntu启动项
  3. HDU 2842 Chinese Rings(矩阵高速功率+递归)
  4. mysql INFORMATION_SCHEMA COLUMNS 解释
  5. 清除防火墙所有配置规则
  6. 图的四种最短路径算法
  7. Java注解Annotation 完成验证
  8. 文件系统管理 之 文件和目录访问权限设置
  9. 如何开启并配置CITRIX Xenserver的SNMP服务
  10. SPI和RAM IP核