批量註冊路由的有個博客說到:https://ainyi.com/77
實際工作中,可能會遇到一個大頁面裏面有很多個模塊,這些模塊一般是需要拆分到單獨的組件中,然後父組件再引入
我最近就遇到一個可以拆分成 10 個模塊的大表單頁面,拆分成局部組件後還是得一個個導入、聲明,最後在 template 應用。作爲一個程序員,我們怎麼能寫這麼一大段重複的代碼呢啊哈哈哈哈
所以就來搞搞局部組件批量註冊和批量應用吧
如圖,一個 Index.vue 文件中需要引入 modules 裏面 10 個子組件
註冊
先掃描讀取目錄下每個文件,如有需要過濾的組件標出,再批量註冊
const requireComponent = require.context('./modules', false, /\w+\.(vue|js)$/)
const cmps = {}
// 這裏我把 CreateHeader 組件排除,單獨引入
const filterCmps = ['./CreateHeader.vue']
requireComponent.keys().forEach(fileName => {
let cmp = requireComponent(fileName).default
!filterCmps.includes(fileName) && (cmps[cmp.name] = cmp)
})
export default {
components: {
createHeader: () => import('./modules/CreateHeader'),
...cmps
},
data() {
return {
// 這裏做排序處理,按原型圖可拆分的模塊順序,將每個組件的 name 命名爲 xxx_${index}
// 爲什麼做排序?爲了循環依次應用子組件
componentList: Object.keys(cmps).sort(
(a, b) => a.split('_')[1] - b.split('_')[1]
)
}
}
}
應用
template 應用手寫每個組件也幾乎不可能了,太多了
上面 componentList 做了排序處理,按照原型圖的順序命名組件的 name: xxx_${index}
有順序了,這裏就可以使用 component、is 依次用 v-for 循環應用
如果每個組件的位置不是排列在一起的(中間穿插其它內容),那就單獨一個個寫吧,也不用做排序
<template>
<div class="krry-appointment">
<create-header :active="active" :translate="translate"></create-header>
<div class="form-content">
<component
v-for="ele in componentList"
:dataSource="dataSource"
:key="ele"
:is="ele"
></component>
</div>
</div>
</template>
這樣就大功告成,是不是簡化了很多代碼~
溫馨提示:如果在上面 v-for 循環的 component 定義 ref,那麼此 $refs 將會是一個數組
<component
ref="formModules"
v-for="ele in componentList"
:dataSource="dataSource"
:key="ele"
:is="ele"
></component>
this.$refs.formModules.forEach(ele => {
// TODO
// 處理每個子組件(ele)
})