使用Element Icon 以及SVG
1. 安装
1.1. 安装 Element Icon
# element-plus/icons-vue
pnpm install @element-plus/icons-vue
# 自动导入
# unplugin-icons
# unplugin-auto-import
pnpm i -D unplugin-icons unplugin-auto-import
1.2. 安装 SVG相关
# vite-plugin-svg-icons
pnpm i -D vite-plugin-svg-icons
2. 配置
2.1. 配置vite.config.ts
import path from 'path';
import Icons from 'unplugin-icons/vite';
import IconsResolver from 'unplugin-icons/resolver';
import AutoImport from 'unplugin-auto-import/vite';
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
const pathSrc = path.resolve(process.cwd(), 'src')
export default defineConfig({
plugins: [
...
createSvgIconsPlugin({
// 指定需要缓存的图标文件夹,根据实际存放位置修改
iconDirs: [path.resolve(process.cwd(), 'src/assets/icons/svg')],
// 指定symbolId格式
symbolId: 'icon-[dir]-[name]',
AutoImport({
resolvers: [
...
// Auto import icon components
// 自动导入图标组件
IconsResolver({
prefix: 'Icon',
}),
],
// 文件释放路径
dts: path.resolve(pathSrc, 'auto-imports.d.ts'),
}),
Components({
resolvers: [
// Auto register icon components
// 自动注册图标组件
IconsResolver({
enabledCollections: ['ep'],
}),
...
],
// 文件释放路径
dts: path.resolve(pathSrc, 'components.d.ts'),
}),
Icons({
autoInstall: true,
}),
],
})
2.2. 引入main.ts
import { createApp } from 'vue';
import App from './App.vue';
// ***********************************************
// SVG需要下面一句
import 'virtual:svg-icons-register';
const app = createApp(App);
app.mount('#app')
3. 使用
3.1. 文件夹存放svg
上一步的vite.config.ts中定义了存放路径,'src/assets/icons/svg'
iconDirs: [path.resolve(process.cwd(), 'src/assets/icons/svg')]
3.2. 创建组件
-
文件夹
-
vue
<script setup lang="ts">
/**
* 输入属性 类型 默认值 是否必选 描述
* name string undefined 是 svg图标名字
* width number 19 否 svg图标宽度
* height number 19 否 svg图标高度
* fill string #ffffff 否 svg图标填充颜色
*/
interface SvgProps {
prefix?: string,
name: string,
width?: string,
height?: string,
color?: string,
}
const props = withDefaults(
defineProps<SvgProps>(),
{
prefix: "#icon-",
name: "",
width: "19px",
height: "19px",
color: "inherit",
}
);
</script>
<template>
<svg aria-hidden="true" :width="width" :height="height">
<use :xlink:href="prefix + name" :fill="color"/>
</svg>
</template>
<style scoped>
</style>
4. 使用
<script setup lang="ts">
...
</script>
<template>
<div>
<SvgIcon name="customerFee" ></SvgIcon>
</div>
</template>
<style scoped>
...
</style>