溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Vue項(xiàng)目中怎么使用異步組件來優(yōu)化性能

發(fā)布時(shí)間:2021-01-19 10:55:56 來源:億速云 閱讀:188 作者:小新 欄目:編程語言

這篇文章將為大家詳細(xì)講解有關(guān)Vue項(xiàng)目中怎么使用異步組件來優(yōu)化性能,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。

在使用JavaScript框架創(chuàng)建大型應(yīng)用程序時(shí),考慮組件結(jié)構(gòu)非常重要。通過考慮組件結(jié)構(gòu),可以避免在運(yùn)行時(shí)加載每個(gè)組件并減慢應(yīng)用程序的速度。在構(gòu)建應(yīng)用程序時(shí),您還可以避免向用戶返回不必要的數(shù)據(jù)或創(chuàng)建整體糟糕的用戶體驗(yàn)。

React和Angular等框架分別使用React.lazy()和路由模型來考慮組件結(jié)構(gòu)。

在這篇文章中,我們將實(shí)現(xiàn)兩個(gè)演示,看看Vue如何使用異步組件,通過使用延遲加載和代碼分割技術(shù)來減少應(yīng)用程序的加載時(shí)間。

在Vue中創(chuàng)建組件

為了理解它是如何工作的,讓我們從創(chuàng)建一個(gè)基本組件開始。

導(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.vueapp.vue。我們將從創(chuàng)建圖書捐贈(zèng)頁面開始。將helloworld.vue重命名為book.vue,并將其內(nèi)容替換為以下內(nèi)容:

<!--Book.vue-->
<template>
  <h2>Donate Books</h2>
</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ì)加載。

接下來,在終端中運(yùn)行npm run serve,導(dǎo)航至localhost:8080,然后查看您的基本組件:

Vue項(xiàng)目中怎么使用異步組件來優(yōu)化性能

現(xiàn)在,每次加載應(yīng)用程序時(shí)加載Book組件似乎不是一個(gè)重要的性能問題。但是,隨著應(yīng)用程序越來越大,在運(yùn)行時(shí)加載每個(gè)組件將變得很麻煩。

您的用戶不會(huì)與應(yīng)用程序中的每個(gè)功能都進(jìn)行交互,因此只提供他們需要的功能是有意義的。問題是,如何只加載用戶需要的內(nèi)容?

這就是延遲加載和代碼分割技術(shù)發(fā)揮作用的地方。延遲加載會(huì)延遲組件的初始加載,在用戶導(dǎo)航到位于頁面上的位置之前,會(huì)阻止加載圖像等資源。

代碼分割是webpack最初提供的一個(gè)特性。Webpack允許您將代碼分割成僅在需要時(shí)使用的各種包。

Vue通過一個(gè)稱為動(dòng)態(tài)導(dǎo)入的特性執(zhí)行代碼分解。

此導(dǎo)入使用webpack(或任何模塊綁定器,如Parcel)異步加載組件。它的語法包含一個(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組件,這使我們能夠異步加載它。 如果我們在瀏覽器devtools中查看“網(wǎng)絡(luò)”標(biāo)簽,則有一個(gè)由App.js發(fā)起的名為0.js的文件。 該文件包含我們的異步組件:

Vue項(xiàng)目中怎么使用異步組件來優(yōu)化性能

使用異步組件創(chuàng)建一個(gè)Vue應(yīng)用程序

讓我們繼續(xù)構(gòu)建一個(gè)基本的圖書捐贈(zèng)應(yīng)用程序,以展示如何利用異步組件。最后,我們只想在用戶單擊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)在,讓我們來構(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ù)組中檢索并顯示。如果用戶單擊每本書的按鈕,addBook()方法將選擇的書推入selectList數(shù)組,并顯示捐贈(zèng)圖書的總數(shù)。

還有一個(gè)單獨(dú)的按鈕,專門用于加載異步組件。它的參數(shù)show設(shè)置為true。這使得v-if語句能夠顯示donate組件,該組件包含所選書籍的數(shù)量。

donate組件已經(jīng)通過<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)用程序編譯成功,在瀏覽器中打開localhost:8080。當(dāng)你在Devtools中查看網(wǎng)絡(luò)標(biāo)簽時(shí)點(diǎn)擊應(yīng)用程序,當(dāng)你點(diǎn)擊Donate按鈕時(shí),Donate組件才會(huì)加載。

異步組件的錯(cuò)誤處理

異步組件需要盡可能簡單,以便快速加載。但是,在我們的異步組件中定義加載和錯(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)連接。為了測試它們是否工作正常,我們將timeout屬性設(shè)置為0,并嘗試加載應(yīng)用程序。

關(guān)于“Vue項(xiàng)目中怎么使用異步組件來優(yōu)化性能”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學(xué)到更多知識,如果覺得文章不錯(cuò),請把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI