1换薄、安裝依賴
npm i @element-plus/icons-vue -S
npm i vite-plugin-svg-icons -D
2、在vite.config.ts文件中
import path from 'path';
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'; // 版本不同引入方式不同
export default defineConfig({
...
plugins: [
...
createSvgIconsPlugin({
// 指定需要緩存的圖標(biāo)文件夾
iconDirs: [path.resolve(process.cwd(), 'src/assets/icons/svg')],
// 指定symbolId格式
symbolId: 'icon-[dir]-[name]'
})
]
});
且按照iconDirs中路徑準(zhǔn)備好svg文件
image.png
3鲜戒、創(chuàng)建引入全部element-plus文件专控,以及創(chuàng)建SvgIcon組件
在components文件夾下創(chuàng)建如下文件
image.png
components/SvgIcon/svgicon.ts文件內(nèi)容如下
// 注冊所有 @element-plus/icons-vue 圖標(biāo)
import * as ElementPlusIconsVue from '@element-plus/icons-vue';
import { App } from 'vue';
export default {
install: (app: App<Element>) => {
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
app.component(key, component);
}
}
};
components/SvgIcon/index.vue文件內(nèi)容如下
// 注冊自定義圖標(biāo)
<template>
<svg :class="svgClass" aria-hidden="true">
<use :xlink:href="iconName" :fill="color" />
</svg>
</template>
<script setup lang="ts">
import { computed } from 'vue';
const props = defineProps({
iconClass: { // 圖標(biāo)名稱與assets/icon/svg下使用的文件名一致
type: String,
required: true
},
className: { // 給圖標(biāo)添加class
type: String,
default: ''
},
color: { // 設(shè)置圖標(biāo)顏色
type: String,
default: '#333'
}
});
const iconName = computed(() => {
return `#icon-${props.iconClass}`;
});
const svgClass = computed(() => {
if (props.className) {
return `svg-icon ${props.className}`;
}
return 'svg-icon';
});
</script>
<style scope lang="scss">
.sub-el-icon,
.nav-icon {
display: inline-block;
font-size: 15px;
margin-right: 12px;
position: relative;
}
.svg-icon {
width: 1em;
height: 1em;
position: relative;
fill: currentColor;
vertical-align: -2px;
}
</style>
4、在main.ts中引入
// 注冊所有圖標(biāo)
import 'virtual:svg-icons-register'; // 引入注冊腳本
import SvgIcon from '@/components/SvgIcon/index.vue';
import elementIcons from '@/components/SvgIcon/svgicon';
app.component('SvgIcon', SvgIcon);
app.use(elementIcons);
5遏餐、使用方法
// 自定義的svg圖標(biāo)
<svg-icon icon-class="lock" class="loack-icon"></svg-icon>
// element-plus圖標(biāo)
<el-icon><user-filled /></el-icon>