nuxt.js的核心代码_Nuxt.js中的通用应用程序代码结构
nuxt.js的核心代碼
by Krutie Patel
通過克魯?shù)佟づ撂貭?Krutie Patel)
Nuxt.js中的通用應(yīng)用程序代碼結(jié)構(gòu) (Universal application code structure in Nuxt.js)
Nuxt.js中的源代碼結(jié)構(gòu)的簡要摘要 (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框架的新手,并且對它附帶的文件夾數(shù)量感到不知所措嗎? 您是否也對其中大多數(shù)文件都為空,而其中僅包含自述文件感到驚訝? 好吧,那是我一年多以前的地方。 從那時起,我一直想學(xué)習(xí)并記錄每個文件夾帶入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.
現(xiàn)在,在使用此框架實施了一些項目之后,我記錄了對這些文件夾如何協(xié)同工作以使服務(wù)器渲染的Vue應(yīng)用程序栩栩如生的理解。
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。 一目了然,您會在“通用應(yīng)用程序代碼”部分中看到不同的文件夾,以及如何通過Nuxt打包并通過Webpack打包代碼。
This article is neither tutorial nor complete guide to Nuxt SSR. It rather shows what goes into universal application.
本文既不是教程,也不是Nuxt SSR的完整指南。 而是顯示了通用應(yīng)用程序中的內(nèi)容。
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預(yù)先與Vuex打包在一起,但是除非您在/ store目錄中創(chuàng)建Vuex商店并創(chuàng)建商店,否則它不會被激活。
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!
對于任何數(shù)據(jù)驅(qū)動的項目,這都是非常特殊的目錄。 在這里您可以創(chuàng)建數(shù)據(jù)存儲,以及定義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.
當(dāng)用戶最初訪問您的應(yīng)用程序時,這有助于填充/更新商店。 它還可以維護整個應(yīng)用程序中數(shù)據(jù)的狀態(tài)。
路由中間件(/中間件) (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配置進入并影響所有路由)
- Layout middleware (entry via layouts and affects group of matching routes, i.e. certain pages only to be viewed/accessed by authenticated users) 布局中間件(通過布局進入并影響一組匹配的路線,即某些頁面僅由經(jīng)過身份驗證的用戶查看/訪問)
- Page middleware (entry via page component and affects single route) 頁面中間件(通過頁面組件進入并影響單個路由)
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.
上面的中間件是按照確切的順序處理的-這意味著它們的優(yōu)先級是不可協(xié)商的。 因此,您必須仔細(xì)考慮并計劃應(yīng)用程序,以充分利用它們。
Vue組件 (Vue Components)
There are three directories where .vue files are created in a Nuxt project.
在Nuxt項目中創(chuàng)建三個目錄的.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.
這是存放應(yīng)用程序視圖和路由的所有目錄中最重要的目錄。 此處創(chuàng)建的Vue.js組件直接轉(zhuǎn)換為應(yīng)用程序路由。
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.
頁面組件的真正力量在于動態(tài)路由。 您可以使用它們來生成SEO友好和面向數(shù)據(jù)的URL。 動態(tài)路由是根據(jù)/ pages下的目錄結(jié)構(gòu)生成的。
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.vueexport 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.
布局組件為應(yīng)用程序的結(jié)構(gòu)方面提供了動力。 在此處創(chuàng)建所有頁面上的通用組件(例如主菜單,輔助菜單,頁眉,頁腳等)。 它們位于/ 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組件,因此您可以在這里發(fā)揮自己的創(chuàng)造力。 不要忘記在布局的主要內(nèi)容區(qū)域添加<nux t />。
<template> <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.
將路由中間件與布局組件相結(jié)合,并存儲數(shù)據(jù)狀態(tài) ,以針對各種場景下的任意數(shù)量的用戶類型構(gòu)建完善的“ 看誰看”功能。 您不僅可以通過自定義用戶界面實現(xiàn)更多目標(biāo)。
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.
這些是常規(guī)但通用的Vue組件。 它們在/ components目錄下創(chuàng)建。 它們不會使用諸如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.
但是它們允許您構(gòu)造和組織業(yè)務(wù)邏輯。 它們還會在頁面和布局組件中隱藏沉重的標(biāo)記。 這使您的代碼庫更易于管理。
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)
現(xiàn)在仔細(xì)觀察-您可以在此Nuxt生命周期圖中看到部分文件夾結(jié)構(gòu)嗎? 提示:存儲(nuxtServerInit),路由中間件和頁面組件(驗證,asyncData和獲取方法)
資產(chǎn) (Assets)
Webpacked資產(chǎn)(/資產(chǎn)) (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文件之類的資產(chǎn),具體取決于文件類型。 例如,如果您以.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,以指示W(wǎng)ebpack在構(gòu)建過程中縮小和優(yōu)化資產(chǎn)文件夾中的圖像。 Webpack處理文件后,它將哈希碼( 例如index.4258e3668a44556dd767.js)附加到已處理的項目,這有助于長期緩存動態(tài)資產(chǎn)和清除緩存。
靜態(tài)資產(chǎn)(/靜態(tài)) (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.
對于不會更改的資產(chǎn),您可以安全地將它們放在靜態(tài)文件夾中。 Webpack會忽略靜態(tài)文件夾,并且不會在其中處理任何內(nèi)容。
模塊,服務(wù)器中間件和插件 (Modules, serverMiddleware and plugins)
They are all defined (by their path) in Nuxt configuration. They are accessible globally within the Nuxt application.
它們都是在Nuxt配置中定義的(通過它們的路徑)。 在Nuxt應(yīng)用程序中可以全局訪問它們。
模塊(/模塊) (Modules (/modules))
A fresh Nuxt application is pre-packaged with Vue, Vue Router, Vuex, Vue Server Rendered and Vue Meta by default.
默認(rèn)情況下,新的Nuxt應(yīng)用程序已預(yù)先打包有Vue,Vue路由器,Vuex,Vue服務(wù)器渲染和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模塊發(fā)揮作用的地方。
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可以被視為您的應(yīng)用程序的擴展點。 它們之所以特別,是因為它們可以訪問連接框架的基礎(chǔ)實例。
Since Nuxt uses connect to deliver the application, it allows custom functions to be hooked into the underlying request pipeline as middleware.
由于Nuxt使用connect來交付應(yīng)用程序,因此它允許將自定義函數(shù)作為中間件掛接到基礎(chǔ)請求管道中。
You can use serverMiddleware to:
您可以使用serverMiddleware來:
- Create an API endpoint to connect to external applications. 創(chuàng)建一個API端點以連接到外部應(yīng)用程序。
- Create an API endpoint to send email to users from your Nuxt application. 創(chuàng)建一個API端點,以從您的Nuxt應(yīng)用程序向用戶發(fā)送電子郵件。
- 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和模塊,您沒有任何預(yù)填充的空文件夾。 您可以在需要時創(chuàng)建它們。
插件(/插件) (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.
您只需將現(xiàn)有的Vue mixin,過濾器或指令轉(zhuǎn)換為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.
但是大多數(shù)時候,您最終會添加外部軟件包或Vue庫作為Nuxt插件。 您只需使用Vue.use()語法將它們合并到Nuxt中。 我經(jīng)常在Nuxt實現(xiàn)中最終使用的一些主要插件是Vue Bootstrap,表單驗證,超棒的圖標(biāo)集和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.
插件還沒有結(jié)束。 您可以編寫自定義插件并將其添加到應(yīng)用程序根目錄中。 它們在您的Nuxt應(yīng)用程序中全局可用。 這是我個人最喜歡的將自定義GreenSock或Scroll-Magic過渡添加到項目中,并在Vue (/組件)和Page (/ pages)組件中使用它們的方式。
模塊,服務(wù)器中間件和插件的高級概述 (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來構(gòu)建應(yīng)用程序。 Nuxt打包您的應(yīng)用程序。
As shown in the diagram below, index.js is the main entry point, which imports app.js.
如下圖所示, index.js是導(dǎo)入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實例。 如果您仔細(xì)查看.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 )將基于該實例創(chuàng)建一個新實例,并將其安裝到DOM元素。 最終用戶會在瀏覽器中看到一個應(yīng)用程序的新實例。 服務(wù)器條目( server.js )為每個請求創(chuàng)建一個新的應(yīng)用程序?qū)嵗?
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捆綁了您的應(yīng)用程序,以使代碼在客戶端和服務(wù)器端均可運行。 服務(wù)器捆綁包呈現(xiàn)服務(wù)器端,而客戶端捆綁包在瀏覽器中合并靜態(tài)HTML標(biāo)記。 它將其轉(zhuǎn)變?yōu)榭梢詫蛻舳藬?shù)據(jù)更改做出React的動態(tài)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為我們提供了開箱即用的功能,因此您無需手動編寫此設(shè)置。 最后兩個步驟涉及很多復(fù)雜性-包裝和捆綁。 但是Nuxt對您隱藏了所有這些內(nèi)容。 您可以集中精力于最終交付最終應(yīng)用程序的應(yīng)用程序代碼。
結(jié)論 (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.
我希望對應(yīng)用程序代碼結(jié)構(gòu)的更高層次的概述可以使您在學(xué)習(xí)Nuxt框架的過程中邁出新一步。
This is one of many alternate perspectives to help you make sense of how everything fits together in a Nuxt application.
這是許多替代觀點之一,可以幫助您理解Nuxt應(yīng)用程序中的所有內(nèi)容如何組合在一起。
For me personally, this little exercise helps me:
對我個人而言,這種小運動可以幫助我:
- map out the requirements of the project against out-of-the-box Nuxt features 根據(jù)開箱即用的Nuxt功能繪制項目需求
- list relevant community modules & plugins that are already available, and 列出已經(jīng)可用的相關(guān)社區(qū)模塊和插件,以及
- pick out the remaining/complex bits that require custom development. 選擇需要定制開發(fā)的其余/復(fù)雜位。
圖表鏈接與上面使用的圖表的高分辨率版本 (Diagrams links with high-res versions of the diagrams used above)
Nuxt Js lifecycle hooks
Nuxt Js生命周期掛鉤
Understanding modules, serverMiddleware and plugins
了解模塊,服務(wù)器中間件和插件
Universal application code in Nuxt.js
Nuxt.js中的通用應(yīng)用程序代碼
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.
歡迎在下面的評論部分中與您想看到的新圖表想法相關(guān)的評論,反饋甚至建議。
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的新手,那么您可能想看看我以前關(guān)于此主題的文章“ 為什么Nuxt Js是您的目標(biāo)網(wǎng)頁的理想框架? 這將使您更深入地了解使用Nuxt開發(fā)應(yīng)用程序的本質(zhì)。
你是納克斯嗎? (Are you Nuxt yet?)
When @_achopin asked at the @vuejsamsterdam, “Are you Nuxt?” I thought, hey… I am Nuxt.
當(dāng)@_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.
我創(chuàng)建了這些Nuxt貼紙 -由Moo Printing專業(yè)印刷,如果您有興趣可以隨時發(fā)貨。 另外,您也可以在RedBubble上訂購它們。
翻譯自: https://www.freecodecamp.org/news/universal-application-code-structure-in-nuxt-js-4cd014cc0baa/
nuxt.js的核心代碼
總結(jié)
以上是生活随笔為你收集整理的nuxt.js的核心代码_Nuxt.js中的通用应用程序代码结构的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到抓了好多活鱼是什么意思
- 下一篇: node.js web框架_使用Node