大致步驟:
1,新建.js文件,使用require提供的函數(shù)context加載某一個(gè)目錄下所有的.vue后綴的文件。
2蔓彩,然后context函數(shù)會(huì)返回一個(gè)導(dǎo)入函數(shù)的ctx,它有一個(gè)keys()方法獲取所有文件路徑踱侣。
3粪小,通過(guò)文件路徑數(shù)組,遍歷數(shù)組抡句,在使用ctx根據(jù)路徑導(dǎo)入組件對(duì)象
4探膊,遍歷的同事進(jìn)行全局注冊(cè)即可。
//參數(shù):1. 在那個(gè)目錄找 2.是否加載子目錄 3.加載的文件名(正則匹配)
export default {
install (app){
//批量注冊(cè)全局組建
//加載該目錄下所有.vue文件
const ctx = require.context('./',false,/\.vue$/)
ctx.keys().forEach(()=>{
//item:組件的地址 ctx(item) 導(dǎo)入這個(gè)組件
const component = ctx(item).default
app.component(component.name , component)
})
}
這樣就能自動(dòng)在文件夾下面找到.vue組件待榔,并且自動(dòng)注冊(cè)了逞壁。
案例
Loading.vue
<template>
<div class="loading">
<a-spin :tip="$t('common.loading')+'...'">
</a-spin>
</div>
</template>
<script>
export default {
name: 'Loading'
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>
.loading {
padding-top:30px;
text-align: center;
}
</style>
index.ts
// 參數(shù):1. 在那個(gè)目錄找 2.是否加載子目錄 3.加載的文件名(正則匹配)
export default {
install(app) {
// 批量注冊(cè)全局組建
// 加載該目錄下所有.vue文件
const ctx = require.context('./', false, /\.vue$/)
ctx.keys().forEach((item) => {
// item:組件的地址 ctx(item) 導(dǎo)入這個(gè)組件
const component = ctx(item).default
debugger
app.component(component.name, component)
})
}
}
main.ts
import Plugins from './plugins'
app.use(Plugins)