Vue 3.0 異步組件

2021-07-16 11:44 更新

#概覽

以下是對變化的高層次概述:

  • 新的 defineAsyncComponent 助手方法,用于顯式地定義異步組件
  • component 選項重命名為 loader
  • Loader 函數(shù)本身不再接收 resolvereject 參數(shù),且必須返回一個 Promise

如需更深入的解釋,請繼續(xù)閱讀!

#介紹

以前,異步組件是通過將組件定義為返回 Promise 的函數(shù)來創(chuàng)建的,例如:

  1. const asyncPage = () => import('./NextPage.vue')

或者,對于帶有選項的更高階的組件語法:

  1. const asyncPage = {
  2. component: () => import('./NextPage.vue'),
  3. delay: 200,
  4. timeout: 3000,
  5. error: ErrorComponent,
  6. loading: LoadingComponent
  7. }

#3.x 語法

現(xiàn)在,在 Vue 3 中,由于函數(shù)式組件被定義為純函數(shù),因此異步組件的定義需要通過將其包裝在新的 defineAsyncComponent 助手方法中來顯式地定義:

  1. import { defineAsyncComponent } from 'vue'
  2. import ErrorComponent from './components/ErrorComponent.vue'
  3. import LoadingComponent from './components/LoadingComponent.vue'
  4. // 不帶選項的異步組件
  5. const asyncPage = defineAsyncComponent(() => import('./NextPage.vue'))
  6. // 帶選項的異步組件
  7. const asyncPageWithOptions = defineAsyncComponent({
  8. loader: () => import('./NextPage.vue'),
  9. delay: 200,
  10. timeout: 3000,
  11. errorComponent: ErrorComponent,
  12. loadingComponent: LoadingComponent
  13. })

對 2.x 所做的另一個更改是,component 選項現(xiàn)在被重命名為 loader,以便準(zhǔn)確地傳達(dá)不能直接提供組件定義的信息。

  1. import { defineAsyncComponent } from 'vue'
  2. const asyncPageWithOptions = defineAsyncComponent({
  3. loader: () => import('./NextPage.vue'),
  4. delay: 200,
  5. timeout: 3000,
  6. error: ErrorComponent,
  7. loading: LoadingComponent
  8. })

此外,與 2.x 不同,loader 函數(shù)不再接收 resolvereject 參數(shù),且必須始終返回 Promise。

  1. // 2.x 版本
  2. const oldAsyncComponent = (resolve, reject) => {
  3. /* ... */
  4. }
  5. // 3.x 版本
  6. const asyncComponent = defineAsyncComponent(
  7. () =>
  8. new Promise((resolve, reject) => {
  9. /* ... */
  10. })
  11. )

有關(guān)異步組件用法的詳細(xì)信息,請參閱:

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號