專案越來越大的時候,可能導致載入速度變慢,這時候可以用動態載入元件和 router 的 lazy loading,讓開啟時更快速。
以詳細資料頁面為例,引入時會寫成以下這個樣子
import DetailModal from './components/DetailModal.vue'
代表一打開頁面就需要把整個詳細資訊都載入,但是使用者可能只是瀏覽列表並沒有點進去看詳細資訊,這樣的載入方式會造成:
「只在需要的時候,才去載入對應的元件或頁面。」
可以使用以下方式來實現延遲載入
import { defineAsyncComponent } from 'vue'
const DetailModal = defineAsyncComponent(() => import('./components/DetailModal.vue'))
<DetailModal>
時,才會去載入那個 .vue 檔案一樣的想法也可以用在 router 上,叫做 Route-level code splitting
從原本的 router,如以下:
import HomeView from '../views/HomeView.vue'
import AboutView from '../views/AboutView.vue'
const routes = [
{ path: '/', component: HomeView },
{ path: '/about', component: AboutView },
]
改為以下:
const routes = [
{ path: '/', component: () => import('../views/HomeView.vue') },
{ path: '/about', component: () => import('../views/AboutView.vue') },
]
在第一次載入時,可能會等一下下,因此可以加入 loading 畫面
const DetailModal = defineAsyncComponent({
loader: () => import('./components/DetailModal.vue'),
loadingComponent: {
template: '<div class="loading">載入中...</div>'
},
delay: 200, // 延遲 0.2 秒再顯示 loading,避免閃爍
timeout: 5000 // 超過 5 秒視為錯誤
})
小結
- 元件延遲載入
- Route-level code splitting
- lazy loading 中加入 loading 畫面