背景
实际开发项目中,有些时候我们需要通过全局注册多个自定义组件,但是每个组件都导入一次,将会导致代码很冗余。
实现方案
customComponents/index.js
const files = import.meta.globEager("@/customComponents/*.vue"); const components = { install: function (app) { for (let compPath in files) { let compName = files[compPath]["default"]["name"]; app.component(compName, files[compPath]["default"]); } }, }; export default components;
main.js
import { createApp } from "vue"; import App from "./App.vue"; import router from "./modules/router"; import pinia from "./modules/pinia"; import components from "@/customComponents"; const app = createApp(App); app.use(router); app.use(pinia); app.use(components); app.mount("#app");
我曾尝试使用 Vue3 的异步组件,使用 import 动态导入,但是会报错,如果有懂的大神帮忙解答下是什么原因
app.component('MyComponent', defineAsyncComponent(() => import('./components/MyComponent.vue') ))
报错:
runtime-core.esm-bundler.js:38 [Vue warn]: Unhandled error during execution of async component loader
at <AsyncComponentWrapper key=0 >
Uncaught (in promise) TypeError: Failed to resolve module specifier '@/customComponents/Button.vue'