vue3 批量导入组件/ elemelt-plus自定义icon图标
该方式对批量导入组件,打包后的路径有问题(开发环境没问题),以下代码仅供参考。如果有哪位有解决路径的方案可以在下面评论区留言,欢迎指导。谢谢!
目录结构如下:
//index.ts 文件
//一般引入
/* import Coupons from "./components/coupons.vue";
import DictionaryConfig from "./components/dictionaryConfig.vue";
import DictionaryManagement from "./components/DictionaryManagement.vue";
import LineManagement from "./components/LineManagement.vue";
import NotificationManagement from "./components/NotificationManagement.vue";
import Overview from "./components/Overview.vue";
import Report from "./components/Report.vue";
import Ticket from "./components/Ticket.vue";
import TicketManagement from "./components/TicketManagement.vue";
import UserManagement from "./components/UserManagement.vue";
export default {
Coupons,
DictionaryConfig,
DictionaryManagement,
LineManagement,
NotificationManagement,
Overview,
Report,
Ticket,
TicketManagement,
UserManagement
}; */
//改成批量导入
import { defineAsyncComponent } from "vue";
//vite 构建
const Files = import.meta.glob("./components/*.vue");
//webpack 构建
// const Files = require.context('./components', false, /\.vue$/)
let module: { [key: string]: any } = {};
const modules = Object.keys(Files).reduce((module, modulePath) => {
const key = modulePath.replace(/^\.\/(.*)\.\w+$/, "$1").split("/")[1]; //modulePath.split("/").pop()?.split(".").shift() + "";
module[key] = defineAsyncComponent(() => import(modulePath));
return modules;
}, module);
export default modules;
其中一组件代码:
Coupons.vue
<template>
<img src="@/assets/icons/Coupons.png" alt="" style="height: inherit" />
</template>
<script setup lang="ts" name="Coupons"></script>
<style scoped lang="scss"></style>
全局导入main.ts
import { createApp } from "vue";
import App from "./App.vue";
// element plus
import ElementPlus from "element-plus";
// element icons
import * as Icons from "@element-plus/icons-vue";
// element css
import "element-plus/dist/index.css";
//自定义icon
import CustomIcons from "@/icons";
const app = createApp(App);
// 注册element Icons组件
Object.keys(Icons).forEach(key => {
app.component(key, Icons[key as keyof typeof Icons]);
});
//注册 自定义图标 组件
Object.keys(CustomIcons).forEach(key => {
app.component(key, CustomIcons[key as keyof typeof CustomIcons]);
});
app.use(ElementPlus).mount("#app");
使用:
<template>
<div class="card content-box">
<icon>
<Coupons />
</icon>
<icon>
<DictionaryConfig />
</icon>
</div>
</template>
局部使用:
<template>
<div class="card content-box">
<!-- 局部引入使用 -->
<icon v-for="(item, index) in Icons" :key="index">
<component :is="item"></component>
</icon>
</div>
</template>
<script setup lang="ts" name="test">
import Icons from "@/icons";
</script>
<style scoped lang="scss">
</style>