天天看點

Vue.js 中使用defineAsyncComponent 延遲加載元件

Vue.js 中使用defineAsyncComponent 延遲加載元件

原文 | https://learnvue.co/2021/06/lazy-load-components-in-vue-with-defineasynccomponent/

使用 vue 3 的 defineAsyncComponent 特性可以讓我們延遲加載元件。這意味着它們僅在需要時從伺服器加載。

這是改善初始頁面加載的好方法,因為我們的應用程式将以較小的塊加載,而不必在頁面加載時加載每個元件。

Vue.js 中使用defineAsyncComponent 延遲加載元件

在本教程中,我們将學習 defineAsyncComponent 的全部内容,并看一個例子,該例子将一個彈出視窗的加載推遲到我們的應用程式需要的時候。

好了,讓我們開始吧。

什麼是defineAsyncComponent

// SOURCE: https://v3.vuejs.org/guide/component-dynamic-async.html
const AsyncComp = defineAsyncComponent(
  () =>
    new Promise((resolve, reject) => {
      resolve({
        template: '<div>I am async!</div>'
      })
    })
)      

defineAsyncComponent 接受一個傳回Promise的工廠函數。當我們成功地從伺服器擷取元件時,這個Promise應該會被 resolve ,如果出現錯誤則會被 reject 。

要使用它,我們必須從Vue中導入它,然後才能在腳本的其餘部分中使用它。

我們也可以使用工廠函數中的 import ,輕松地從其他檔案中添加Vue元件。

import { defineAsyncComponent } from "vue" 


// 簡單使用
const LoginPopup = defineAsyncComponent(() => import("./components/LoginPopup.vue"))      

這是使用 defineAsyncComponent 的最簡單方法,但我們也可以傳入一個完整的選項對象,配置幾個更進階的參數。

// with options 
const AsyncPopup = defineAsyncComponent({ 
  loader: () => import("./LoginPopup.vue"),
  loadingComponent: LoadingComponent, /* 在加載時顯示 */
  errorComponent: ErrorComponent, /* 顯示是否有錯誤 */
  delay: 1000, /* 在顯示加載元件之前延遲毫秒 */
  timeout: 3000 /* 這個毫秒之後的逾時 */
})      

就我個人而言,我發現自己更經常使用第一種較短的文法,它對我的大多數使用情況都有效,但這完全取決于你。

就這麼簡單,讓我們進入我們的例子。

使用defineAsyncComponent延遲加載彈出元件

在本例中,我們将使用一個由單擊按鈕觸發的登入彈出視窗。

每當我們的應用程式加載時,我們不需要我們的應用程式加載此元件,因為隻有在使用者執行特定操作時才需要它。

是以這就是我們的登入元件的樣子,它隻是通過用 position: fixed 将螢幕的其餘部分塗黑來建立一個彈出視窗,并且有一些輸入和一個送出按鈕。

<template>
  <div class="popup">
    <div class="content">
      <h4> Login to your account </h4>
      <input type="text" placeholder="Email" />
      <input type="password" placeholder="Password" />
      <button> Log in </button>
    </div>
  </div>
</template>


<script>
</script>


<style scoped>
.popup {
  position: fixed;
  width: 100%;
  top: ; 
  left: ;
  height: 100%;
  background-color: rgba(, , , 0.2);
  display: flex;
  justify-content: center;
  align-items: center;
}
.content {
   min-width: 200px;
   width: 30%;
   background: #fff;
   height: 200px;
   padding: 10px;
   border-radius: 5px;
}
input[type="text"], input[type="password"] {
  border: ;
  outline: ;
  border-bottom: 1px solid #eee;
  width: 80%;
  margin:  auto;
  font-size: 0.5em;
}
button {
  border: ;
  margin-top: 50px;
  background-color:#8e44ad;
  color: #fff;
  padding: 5px 10px;
  font-size: 0.5em;
}
</style>      
Vue.js 中使用defineAsyncComponent 延遲加載元件

而不是像我們通常那樣導入它并将其納入我們的 components 選項中。

<!-- "Standard" way of doing things -->
<template>
  <button @click="show = true"> Login </button>
  <login-popup v-if="show" />
</template>


<script>
import LoginPopup from './components/LoginPopup.vue'
export default {
  components: { LoginPopup },
  data() {
    return {
      show: false
    }
  }
}
</script>      

我們可以改為使用 defineAsyncComponent 僅在需要時加載它(意味着單擊按鈕并切換我們的 v-if)。

<!-- Use defineAsyncComponent  -->
<template>
  <button @click="show = true"> Login </button>
  <login-popup v-if="show" />
</template>


<script>
import { defineAsyncComponent } from 'vue'
export default {
  components: { 
    "LoginPopup" : defineAsyncComponent(() => import('./components/LoginPopup.vue'))
  },
  data() {
    return {
      show: false
    }
  }
}
</script>      

雖然這在我們使用我們的應用程式時可能看起來是一樣的,但讓我們檢查元素 > 網絡來了解這個小而重要的差別。

如果我們不使用 defineAsyncComponent,一旦我們的頁面加載,我們就會看到我們的應用程式從伺服器上獲得LoginPopup.vue。

雖然在這個例子中,這可能不是最大的性能問題,但它仍然會減慢加載速度,如果我們有幾十個元件這樣做,它真的會加起來。

Vue.js 中使用defineAsyncComponent 延遲加載元件

但是,如果我們使用 defineAsyncComponent 檢視同一個頁籤,我們會注意到當我們的頁面加載時,LoginPopup.vue 不見了,這是因為它還沒有加載。

Vue.js 中使用defineAsyncComponent 延遲加載元件

但是一旦我們點選我們的按鈕并告訴我們的應用程式顯示我們的彈出視窗,這時它就會從伺服器加載,我們可以在網絡标簽中看到它。

Vue.js 中使用defineAsyncComponent 延遲加載元件

這有助于我們實作最佳性能。我們隻想在我們的頁面初始加載時加載需要的元件。有條件渲染的元件在我們的頁面加載時往往是不需要的,是以為什麼要讓我們的應用程式加載它們呢?

如何使用異步設定功能

無論我們是否使用 defineAsyncComponent 延遲加載,任何具有異步設定功能的元件都必須用 <Suspense> 包裝。

簡而言之,建立一個異步設定函數是我們的一個選擇,可以讓我們的元件在渲染前等待一些API調用或其他異步動作。

這是我們具有異步設定的元件。它使用 setTimeout() 模拟 API 調用。

<template>
  <div class="popup">
    <div class="content">
      <p> Loaded API: {{ article }} </p>
      <h4> Login to your account </h4>
      <input type="text" placeholder="Email" />
      <input type="password" placeholder="Password" />
      <button> Log in </button>
    </div>
  </div>
</template>


<script>
const getArticleInfo = async () => {
  // wait 3 seconds to mimic API call
  await new Promise(resolve => setTimeout(resolve, 1000));
  const article = {
    title: 'My Vue 3 Article',
    author: 'Matt Maribojoc'
  }
  return article
}
export default {
  async setup() {
    const article = await getArticleInfo()
    console.log(article)
    return {
      article
    }
  }
}
</script>      

我們可以在有或沒有 defineAsyncComponent 的情況下将它導入到我們的元件中。

import LoginPopup from './components/LoginPopup.vue'
// OR 
const LoginPopup = defineAsyncComponent(() => import("./components/LoginPopup.vue"))      

但是如果我們想讓它在我們的模闆中渲染,我們需要将它包裝在一個 Suspense 元素中。這将等待我們的 setup 函數在嘗試渲染我們的元件之前解析。

<template>
  <button @click="show = true"> Login </button>
  <Suspense v-if="show">
    <template #default>
      <login-popup  />
    </template>
    <template #fallback>
      <p> Loading... </p>
    </template>
  </Suspense>
</template>      

這就是結果。使用者會看到 "正在加載......",然後在3秒後(我們的setTimeout的寫死值),我們的元件将渲染。

預設情況下,我們使用 defineAsyncComponent 定義的所有元件都是可暫停的。

這意味着如果一個元件的父鍊中有 Suspense,它将被視為該 Suspense 的一個異步依賴。我們的元件的加載、錯誤、延遲和逾時選項将被忽略,而是由 Suspense 來處理。

最後的想法

defineAsyncComponent 在建立有幾十個元件的大型項目時是有好處的。當我們進入到懶惰加載元件時,我們可以有更快的頁面加載時間,改善使用者體驗,并最終提高你的應用程式的保留率和轉換率。

學習更多技能

請點選下方公衆号

繼續閱讀