vue動態組件

概述

最近用nuxt.js搞服務端渲染,研究了一下vue的動態組件,記錄下來供之後開發時參考,相信對其餘人也有用。javascript

參考資料:html

vue.js 動態組件 & 異步組件vue

vuejs 內置組件 componentjava

Code Splittingwebpack

原理

動態組件的原理是利用 webpack 的 code spliting 將動態加載的組件分塊打包,而後當代碼執行到這裏的時候用ajax請求對應的地址。web

方法

有以下三種方法實現動態組件:ajax

方法一,利用resolve直接在單文件組件的component裏面引入便可。session

components: {
  PaymentBoard,
  PaymentForm: resolve => require(['@/components/payment/PaymentForm'], resolve),
},

方法二是利用import引入,這種方式其實就是方法一的語法糖異步

components: {
  PaymentBoard,
  PaymentForm: () => import('@/components/payment/PaymentForm'),
},

方法三是使用vue內置的component組件,在mounted階段動態引入:async

<!-- 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,
},
相關文章
相關標籤/搜索