思路:
1、使用 require 提供的函数 context 加载某一个目录下的所有 .vue 后缀的文件。
2、 context 函数会返回一个导入函数 importFn
3、它有一个方法 keys() 获取所有的文件路径
4、通过文件路径数组,通过遍历数组,再使用 importFn 根据路径导入组件对象
5、遍历的同时进行全局注册即可
// require.context() 在哪个目录找 2.是否加载子目录 3.加载的文件名(正则匹配)
const importFn = require.context('./', false, /\.vue$/)
export default {
install (app) {
// 根据keys批量注册
importFn.keys().forEach(path => {
// 导入组件
const component = importFn(path).default
// 组件全局注册
app.component(component.name, component)
})
}
}
接着在main.js中使用
import XXX from '@/components/library'
createApp(App).use(XXX)