大致步骤:
1,新建.js文件,使用require提供的函数context加载某一个目录下所有的.vue后缀的文件。
2,然后context函数会返回一个导入函数的ctx,它有一个keys()方法获取所有文件路径。
3,通过文件路径数组,遍历数组,在使用ctx根据路径导入组件对象
4,遍历的同事进行全局注册即可。
//参数:1. 在那个目录找 2.是否加载子目录 3.加载的文件名(正则匹配)
export default {
install (app){
//批量注册全局组建
//加载该目录下所有.vue文件
const ctx = require.context('./',false,/\.vue$/)
ctx.keys().forEach(()=>{
//item:组件的地址 ctx(item) 导入这个组件
const component = ctx(item).default
app.component(component.name , component)
})
}
这样就能自动在文件夹下面找到.vue组件,并且自动注册了。
案例
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
// 参数:1. 在那个目录找 2.是否加载子目录 3.加载的文件名(正则匹配)
export default {
install(app) {
// 批量注册全局组建
// 加载该目录下所有.vue文件
const ctx = require.context('./', false, /\.vue$/)
ctx.keys().forEach((item) => {
// item:组件的地址 ctx(item) 导入这个组件
const component = ctx(item).default
debugger
app.component(component.name, component)
})
}
}
main.ts
import Plugins from './plugins'
app.use(Plugins)