概述
最近用nuxt.js搞服務端渲染,研究了一下vue的動態組件,記錄下來供以后開發時參考,相信對其他人也有用。
參考資料:
原理
動態組件的原理是利用 webpack 的 code spliting 將動態加載的組件分塊打包,然后當代碼執行到這里的時候用ajax請求對應的地址。
方法
有如下三種方法實現動態組件:
方法一,利用resolve直接在單文件組件的component里面引入即可。
components: {
PaymentBoard,
PaymentForm: resolve => require(['@/components/payment/PaymentForm'], resolve),
},
方法二是利用import引入,這種方式其實就是方法一的語法糖
components: {
PaymentBoard,
PaymentForm: () => import('@/components/payment/PaymentForm'),
},
方法三是使用vue內置的component組件,在mounted階段動態引入:
<!-- template -->
<component
:is="componentName"
:selectedCatsSum="selectedCatsSum"
:selectedNegotiatedSecondCatsSum="selectedNegotiatedSecondCatsSum"
:selectedNegotiatedThirdCatsSum="selectedNegotiatedThirdCatsSum"
:selectedCatsDiscount="selectedCatsDiscount"
:selectedCatsPrice="selectedCatsPrice"
:selectedCats="selectedCats"
/>
// script
mounted() {
this.componentName = () => import('@/components/payment/PaymentForm');
const selectedCats = this.sessionStorageGet('selectedCats');
if (selectedCats) this.selectedCats = selectedCats;
this.init();
},
工廠函數形式的動態組件
還可以使用如下工廠函數形式的動態組件:
const AsyncComponent = () => ({
// 需要加載的組件 (應該是一個 `Promise` 對象)
component: import('./MyComponent.vue'),
// 異步組件加載時使用的組件
loading: LoadingComponent,
// 加載失敗時使用的組件
error: ErrorComponent,
// 展示加載時組件的延時時間。默認值是 200 (毫秒)
delay: 200,
// 如果提供了超時時間且組件加載也超時了,
// 則使用加載失敗時使用的組件。默認值是:`Infinity`
timeout: 3000
});
components: {
AsyncComponent,
},