有两种导入方式:
第一种:异步导入(在需要显示该组件的时候发起请求该组件的js请求)
import { defineAsyncComponent } from 'vue'
const install = (app) => {
//导入指定文件夹中的所有vue文件
const modules = import.meta.glob('./**/*.vue')
//循环注册所有的vue文件
for (const [key, value] of Object.entries({ ...modules })) {
const name = key.slice(key.lastIndexOf('/') + 1, key.lastIndexOf('.'))
app.component(name, defineAsyncComponent(value))
}
}
- 优点:加速了首屏渲染速度,只加载当前需要显示的内容
- 缺点:当使用过程中突然网络不好或者异常了,组件或弹框无法显示出来,或加载很慢
第二种:同步导入(首屏一次性加载全部的组件)
const install = (app) => {
//导入指定文件夹中的所有vue文件
const modules = import.meta.glob('./**/*.vue', { eager: true })
//循环注册所有的vue文件
for (const [key, value] of Object.entries({ ...modules })) {
const name = key.slice(key.lastIndexOf('/') + 1, key.lastIndexOf('.'))
app.component(name, value.default)
}
}
- 优点:当首屏渲染完成后,使用过程中打开其他组件显示不会受到网络的任何影响
- 缺点:首屏加载速度变慢