1、在components文件夹中新建index.ts文件(components文件夹下为创建的组件)
// index.ts
const modules = import.meta.globEager("./*.vue"); //参数为组件路径
let componentsOpts = {}const getCaption = (obj, str, z: boolean) => {let index = obj.lastIndexOf(str);if (z) index += str.length// z为true则截取/之后的内容,反之obj = z ? obj.substring(index, obj.length) : obj.substring(0, index);return obj;
};for (let path in modules) {let str = getCaption(path, './', true)str = getCaption(str, '.vue', false)componentsOpts[str] = modules[path]['default']
}export default componentsOpts
2、在vue文件中引入组件
// list.vue
<script setup lang='ts'>
import componentObj from './components'// const 组件名称 = componentObj['组件文件名称']
const ContentMain = componentObj['main']</script><template><div><content-main ></content-main></div>
</template><style scoped lang='scss'></style>