批量注册组件

57 阅读1分钟

文件放在/library/index.js 本代码用来自动加载注册 在/library文件夹下的组件,

image.png

// 使用 require 提供的函数 context 加载某一个目录下的所有 .vue 后缀的文件。

// 然后 context 函数会返回一个导入函数 importFn

// 它又一个属性 keys() 获取所有的文件路径

// 通过文件路径数组,通过遍历数组,再使用 importFn 根据路径导入组件对象

// 遍历的同时进行全局注册即可

  


// context(目录路径,是否加载子目录,加载文件的匹配正则)

const importFn = require.context('./', false, /\.vue$/)

console.log(importFn.keys(), 'importFn')

  


export default {

install (app) {

// 在app上进行扩展,app提供 component directive 函数

// 如果要挂载原型 app.config.globalProperties 方式

// app.component(XtxSkeleton.name, XtxSkeleton)

// app.component(XtxCarousel.name, XtxCarousel)

// app.component(XtxMore.name, XtxMore)

// app.component(XtxBread.name, XtxBread)

// app.component(XtxBreadItem.name, XtxBreadItem)

  


// 根据key批量注册

importFn.keys().forEach(path => {

const component = importFn(path).default

app.component(component.name, component)

})