vue3中全局注册组件如何实现按需导入多个组件?
如题:
我自定义了很多组件,想全部实现全局注册,但是由于组件过多,不想一个一个导入并注册,有什么办法可以实现按需导入?通过遍历一次性注册?
一个一个导入并注册实现方法:
import Button from "@/customComponents/Button.vue";import Text from "@/customComponents/Text.vue";
import Icon from "@/customComponents/Icon.vue";
import Image from "@/customComponents/Image.vue";
const components = {
install: function (app) {
app.component("Button", Button).component("Text", Text).component("Icon", Icon).component("Image", Image);
},
};
export default components;
这样注册是没问题的!
通过遍历来注册,我的实现方法:
const componentsList = ["Button", "Text", "Icon", "Image"];const components = {
install: function (app) {
componentsList.forEach((componentName) => {
app.component(componentName, () => import(`@/customComponents/${componentName}.vue`));
});
},
};
export default components;
这样的方法,就会导致注册失败,从而使用的时候报错:
回答:
这是一个老问题了。
import 不支持动态地址,在产物分析阶段没有引入你说的那几个资源,所以最后用不了
一般是通过来 require 实现
export const loadview = (path)=>{ return ()=> Promise.resolve(require(`${path}`).default)
}
而且使用的地方也不用你自己写所有的组件,require.context 还是什么可以拿到所有目录吧。
但是这样性能好像不太好

类似问题
- https://zhuanlan.zhihu.com/p/486945512
- https://blog.csdn.net/web_ding/article/details/115344928
- https://www.imooc.com/article/294778/
- https://www.baidu.com/s?ie=UTF-8&wd=import%20%E5%8A%A8%E6%80%...
vue3 看这里,需要 defineAsyncComponent https://cn.vuejs.org/guide/components/async.html#basic-usage
import { defineAsyncComponent } from 'vue'const AsyncComp = defineAsyncComponent(() =>
import('./components/MyComponent.vue')
)


本文参与了SegmentFault 思否面试闯关挑战赛,欢迎正在阅读的你也加入。
回答:
试试用 defineAsyncComponent,如
import { defineAsyncComponent } from 'vue'app.component(componentName, defineAsyncComponent(() => import(`@/customComponents/${componentName}.vue`)));
回答:
用这个antfu/unplugin-vue-components: ? On-demand components auto importing for Vue (github.com), 按需自动引入组件
以上是 vue3中全局注册组件如何实现按需导入多个组件? 的全部内容, 来源链接: utcz.com/p/933881.html
