在使用JavaScript框架創(chuàng)建大型應(yīng)用程序時(shí),考慮組件結(jié)構(gòu)非常重要。通過(guò)考慮組件結(jié)構(gòu),可以避免在運(yùn)行時(shí)加載每個(gè)組件并減慢應(yīng)用程序的速度。在構(gòu)建應(yīng)用程序時(shí),您還可以避免向用戶(hù)返回不必要的數(shù)據(jù)或創(chuàng)建整體糟糕的用戶(hù)體驗(yàn)。
React和Angular等框架分別使用React.lazy()
和路由模型來(lái)考慮組件結(jié)構(gòu)。
在這篇文章中,我們將實(shí)現(xiàn)兩個(gè)演示,看看Vue如何使用異步組件,通過(guò)使用延遲加載和代碼分割技術(shù)來(lái)減少應(yīng)用程序的加載時(shí)間。
在Vue中創(chuàng)建組件
為了理解它是如何工作的,讓我們從創(chuàng)建一個(gè)基本組件開(kāi)始。
導(dǎo)航到您的終端,安裝Vue的CLI,并創(chuàng)建一個(gè)項(xiàng)目:
npm install -g vue/cli vue create book-project #choose the default setting when prompted
在我們的新項(xiàng)目文件夾中,讓我們替換默認(rèn)文件的內(nèi)容,其中包括helloworld.vue
和app.vue
。我們將從創(chuàng)建圖書(shū)捐贈(zèng)頁(yè)面開(kāi)始。將helloworld.vue
重命名為book.vue
,并將其內(nèi)容替換為以下內(nèi)容:
<!--Book.vue--> <template> <h1>Donate Books</h1> </template>
然后,用以下內(nèi)容替換App.vue
的內(nèi)容:
<!--App.vue--> <template> <div> <book></book> </div> </template> <script> Import Book from "./components/Book" export default { components: { Book } } </script> <style> #app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>
在上面的代碼塊中,您會(huì)注意到Book
組件是靜態(tài)導(dǎo)入的。 這意味著Book
組件在每次加載應(yīng)用程序時(shí)都會(huì)加載。
接下來(lái),在終端中運(yùn)行npm run serve
,導(dǎo)航至localhost:8080
,然后查看您的基本組件:
現(xiàn)在,每次加載應(yīng)用程序時(shí)加載Book
組件似乎不是一個(gè)重要的性能問(wèn)題。但是,隨著應(yīng)用程序越來(lái)越大,在運(yùn)行時(shí)加載每個(gè)組件將變得很麻煩。
您的用戶(hù)不會(huì)與應(yīng)用程序中的每個(gè)功能都進(jìn)行交互,因此只提供他們需要的功能是有意義的。問(wèn)題是,如何只加載用戶(hù)需要的內(nèi)容?
這就是延遲加載和代碼分割技術(shù)發(fā)揮作用的地方。延遲加載會(huì)延遲組件的初始加載,在用戶(hù)導(dǎo)航到位于頁(yè)面上的位置之前,會(huì)阻止加載圖像等資源。
代碼分割是webpack最初提供的一個(gè)特性。Webpack允許您將代碼分割成僅在需要時(shí)使用的各種包。
Vue通過(guò)一個(gè)稱(chēng)為動(dòng)態(tài)導(dǎo)入的特性執(zhí)行代碼分解。
此導(dǎo)入使用webpack(或任何模塊綁定器,如Parcel)異步加載組件。它的語(yǔ)法包含一個(gè)承諾,并包裝在一個(gè)箭頭函數(shù):
// dynamic import import("./components/Book").then(Book => { // Insert the Book module here });
讓我們實(shí)現(xiàn)這個(gè)在我們的App.vue組件:
<template> <div> <book></book> </div> </template> <script> export default { components: { Book: () => import("./components/Book") } }; </script>
在上面的代碼示例中,import()
函數(shù)返回Book
組件,這使我們能夠異步加載它。 如果我們?cè)跒g覽器devtools
中查看“網(wǎng)絡(luò)”標(biāo)簽,則有一個(gè)由App.js
發(fā)起的名為0.js
的文件。 該文件包含我們的異步組件:
使用異步組件創(chuàng)建一個(gè)Vue應(yīng)用程序
讓我們繼續(xù)構(gòu)建一個(gè)基本的圖書(shū)捐贈(zèng)應(yīng)用程序,以展示如何利用異步組件。最后,我們只想在用戶(hù)單擊Donate
按鈕時(shí)加載Donate
組件。
首先,讓我們導(dǎo)航到終端并在我們的項(xiàng)目文件夾中安裝vue-material
。我們將使用這個(gè)樣式的應(yīng)用程序:
cd book-project npm i vue-material
我們將在應(yīng)用程序中包括vue-material
導(dǎo)入它在src/main.js
:
import Vue from 'vue' import App from './App.vue' Vue.config.productionTip = false import VueMaterial from 'vue-material' import 'vue-material/dist/vue-material.min.css' import 'vue-material/dist/theme/default.css' Vue.use(VueMaterial) new Vue({ render: h => h(App), }).$mount('#app')
現(xiàn)在,讓我們來(lái)構(gòu)建之前創(chuàng)建的Book
組件:
<!--Book.vue--> <template> <div id="app"> <md-card md-with-hover v-for="(book, key) in books" v-bind:key="key"> <md-ripple> <md-card-header> <div class="md-title">{{book.name}}</div> <div class="md-subhead">{{book.genre}}</div> </md-card-header> <md-card-actions> <md-button type="primary" @click="addBook(key)">Donate to improve {{book.genre}}</md-button> </md-card-actions> </md-ripple> </md-card> <div v-if="show"> <md-card-content> <donate v-bind:selectList="selectList"></donate> </md-card-content> </div> <md-button @click="show = true" id="donate">Donate {{selectList.length}} book(s)</md-button> </div></template> <script> export default { name: 'RegularButtons', methods: { addBook (key) { if(!this.selectList.includes(key)) { this.selectList.push(key); } } }, components: { donate: () => import('./Donate') }, data: () => ({ books: [ { name: 'Using Creatine', genre: 'Workouts' }, { name: 'Learn Parkour', genre: 'Sports' }, { name: 'Snorkelling', genre: 'Diving' }, ], selectList: [], show: false }) } </script>
在上面的代碼塊中,圖書(shū)列表從圖書(shū)數(shù)組中檢索并顯示。如果用戶(hù)單擊每本書(shū)的按鈕,addBook()
方法將選擇的書(shū)推入selectList
數(shù)組,并顯示捐贈(zèng)圖書(shū)的總數(shù)。
還有一個(gè)單獨(dú)的按鈕,專(zhuān)門(mén)用于加載異步組件。它的參數(shù)show
設(shè)置為true
。這使得v-if
語(yǔ)句能夠顯示donate
組件,該組件包含所選書(shū)籍的數(shù)量。
donate
組件已經(jīng)通過(guò)<script>
標(biāo)記中的components
屬性動(dòng)態(tài)導(dǎo)入。
讓我們創(chuàng)建donate
組件。在src/components
文件夾中,創(chuàng)建一個(gè)名為Donate
的新文件。并輸入下面的代碼示例:
<template> <div title="Donate Books" key="donate"> <p v-for="(x, y) in this.selectList" :key="y"> Tip: {{books[Number(x)].name}} is about {{books[Number(x)].genre}} </p> </div> </template> <script> export default { props: ['selectList'], data: () => ({ books: [ { name: 'Using Creatine', genre: 'Workouts' }, { name: 'Learn Parkour', genre: 'Sports' }, { name: 'Snorkelling', genre: 'Underwater' }, ] }) } </script>
導(dǎo)航到您的終端并運(yùn)行npm run serve
。
如果應(yīng)用程序編譯成功,在瀏覽器中打開(kāi)localhost:8080
。當(dāng)你在Devtools
中查看網(wǎng)絡(luò)標(biāo)簽時(shí)點(diǎn)擊應(yīng)用程序,當(dāng)你點(diǎn)擊Donate
按鈕時(shí),Donate
組件才會(huì)加載。
異步組件的錯(cuò)誤處理
異步組件需要盡可能簡(jiǎn)單,以便快速加載。但是,在我們的異步組件中定義加載和錯(cuò)誤組件有助于處理加載狀態(tài)并在需要時(shí)顯示錯(cuò)誤消息。
In src/components, let's create two components: LoadingState.vue and ErrorState.vue:
<!--LoadingState.vue--> <template> <p><em>Loading...</em></p> </template>
<!--ErrorState.vue--> <template> <p>Could not display books. Kindly check your internet conection.</p> </template>
現(xiàn)在,在App.vue
中,我們將導(dǎo)入兩個(gè)組件并將它們添加到Book
組件中:
<!--App.vue--> <script> import LoadingState from "./components/LoadingState" import ErrorState from "./components/ErrorState" const Book = import("./components/Book") export default { components: { Book: () => ({ // Book is our default component component: Book, // LoadingState is the component that is displayed while our default component // is loading loading: LoadingState, // ErrorState is the component that is displayed should our default component have an // error while loading error: ErrorState, // A delay is set up before the loading component is shown delay: 100, // Should this timeout be reached, the default component is considered to have failed // to load timeout: 2000 }) } }; </script>
加載和錯(cuò)誤狀態(tài)不會(huì)出現(xiàn),除非你有一個(gè)非常緩慢或錯(cuò)誤的互聯(lián)網(wǎng)連接。為了測(cè)試它們是否工作正常,我們將timeout屬性設(shè)置為0,并嘗試加載應(yīng)用程序。
結(jié)論
使用異步組件構(gòu)建大型應(yīng)用程序是保持性能的關(guān)鍵。異步組件不僅可以確保由于更快的加載時(shí)間,您的保留率會(huì)更高,而且還可以幫助您更有效地檢測(cè)錯(cuò)誤,因?yàn)榻M件的作用域是作為函數(shù)傳遞的。如果你想看看這個(gè)演示的源代碼,你可以在GitHub上找到它。
相關(guān)推薦:
2020年前端vue面試題大匯總(附答案)
vue教程推薦:2020最新的5個(gè)vue.js視頻教程精選
更多編程相關(guān)知識(shí),請(qǐng)?jiān)L問(wèn):編程入門(mén)??!
文章題目:Vue項(xiàng)目中使用異步組件來(lái)優(yōu)化性能
文章網(wǎng)址:http://chinadenli.net/article42/cjpjhc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供品牌網(wǎng)站建設(shè)、企業(yè)網(wǎng)站制作、網(wǎng)站收錄、微信小程序、手機(jī)網(wǎng)站建設(shè)、網(wǎng)站導(dǎo)航
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)