defineAsyncComponent 異步組件

Vue Router 支持開箱即用的動態(tài)導入,這意味著你可以用動態(tài)導入代替靜態(tài)導入:
// 將// import UserDetails from './views/UserDetails'// 替換成const UserDetails = () => import('./views/UserDetails')const router = createRouter({// ...routes: [{ path: '/users/:id', component: UserDetails }],})
component (和 components) 配置接收一個返回 Promise 組件的函數(shù),Vue Router 只會在第一次進入頁面時才會獲取這個函數(shù),然后使用緩存數(shù)據(jù)。
一般來說,對所有的路由都使用動態(tài)導入是個好主意。
注意:不要在路由中使用異步組件。異步組件仍然可以在路由組件中使用,但路由組件本身就是動態(tài)導入的。
Vue3 支持 defineAsyncComponent() 方法定義一個異步組件,它在運行時是懶加載的。參數(shù)可以是一個加載函數(shù),或是對加載行為有更進一步控制的一個選項對象。
在大型項目中,我們可能需要拆分應用為更小的塊,并僅在需要時再從服務器加載相關組件。為實現(xiàn)這點,Vue 提供了一個 defineAsyncComponent 方法:
import { defineAsyncComponent } from 'vue'const AsyncComp = defineAsyncComponent(() => {return new Promise((resolve, reject) => {// ...從服務器獲取組件resolve(/* 獲取到的組件 */)})})// ... 像使用其他一般組件一樣使用 `AsyncComp`
如你所見,defineAsyncComponent 方法接收一個返回 Promise 的加載函數(shù)。這個 Promise 的 resolve 回調(diào)方法應該在從服務器獲得組件定義時調(diào)用。你也可以調(diào)用 reject(reason) 表明加載失敗。
對于 defineAsyncComponent 使用場景,有的需求會想要在兩個組件間來回切換,比如 Tab 界面:
<component :is="currentTab">component>
上面的例子是通過 Vue 的動態(tài)組件實現(xiàn)視圖切換的。
<script lang="ts">import { ref, defineAsyncComponent } from 'vue'const AsyncComp1 = defineAsyncComponent(() =>import('./components/MyComponent1.vue'))const AsyncComp2 = defineAsyncComponent(() =>import('./components/MyComponent2.vue'))export default {components: {AsyncComp1,AsyncComp2},setup() {const currentTab = ref('AsyncComp1')function change() {currentTab.value = currentTab.value === 'AsyncComp1' ? 'AsyncComp2' : 'AsyncComp1'}return {currentTab,change}}script><template><div><div @click="change">視圖切換div><component :is="currentTab">component>div>template>
但是下面這里是一個 React 的例子,展示如何在你的應用中使用 React.lazy 和 React Router 這類的第三方庫,來配置基于路由的代碼分割。
import React, { Suspense, lazy } from 'react';import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';const Home = lazy(() => import('./routes/Home'));const About = lazy(() => import('./routes/About'));const App = () => (Loading...
} /> } /> );由于 React Router 沒有支持動態(tài)導入,所以直接使用 import 語法是不可以的,必須借助 React.lazy 函數(shù)能讓你像渲染常規(guī)組件一樣處理動態(tài)引入(的組件)
