封装文件内:
import {getAsyncComponent} from "@/utils";
import {Plugin} from "vue";
// 要异步导入的全局组件
const asyncComponentPathArr = [
{
name: "PersonalCenter",
path: '../components/PersonalCenter/PersonalCenter.vue'
}
]
// app.use一次性注册多个全局组件
const asyncComponentsPlugin: Plugin = {
install(app) {
for (let item of asyncComponentPathArr) {
app.component(item.name, getAsyncComponent(item.path))
}
}
}
export default asyncComponentsPlugin
getAsyncComponent方法里面:
// 获取异步组件
export const getAsyncComponent = (path: string) => {
return defineAsyncComponent(() => import(/* @vite-ignore */path))
}
main.js引入:
每次只需要给asyncComponentPathArr数组添加name元素和path即可;
参考vue3文档:动态组件 & 异步组件 | Vue.js