直接贴代码
对应的插件
pnpm i vite-plugin-svg-icons -D
pnpm i fast-glob -D
vite 添加一下配置
import {fileURLToPath, URL} from 'node:url'
import {defineConfig} from 'vite'
import vue from '@vitejs/plugin-vue'
import {resolve} from "path"
import {createSvgIconsPlugin} from 'vite-plugin-svg-icons'
export default defineConfig({
plugins: [
vue(),
createSvgIconsPlugin({
// 这个是自己配置的图标路径,指出来(自己咋配置的咋来)
iconDirs: [resolve('src/assets/icons/svg')],
// 这个表示id,按这个来就对了
symbolId: 'icon-[dir]-[name]'
})
]
})
然后在组件包下创建一个 svg 的组件
<template>
<svg :class="svgClass" v-bind="$attrs" :style="{ color: color }">
<use :xlink:href="iconName"/>
</svg>
</template>
<script setup>
import {computed} from 'vue'
const props = defineProps({
name: {
type: String,
required: true
},
color: {
type: String,
default: ''
}
})
const iconName = computed(() => `#icon-${props.name}`)
const svgClass = computed(() => {
if (props.name) {
return `svg-icon icon-${props.name}`
}
return 'svg-icon'
})
</script>
<style scoped>
.svg-icon {
width: 1em;
height: 1em;
fill: currentColor;
vertical-align: middle;
}
</style>
最后在 mian.js 全局注册 svg
// 全局 svgIcon
import 'virtual:svg-icons-register'
import SvgIcon from '@/components/SvgIcon/index.vue'// svg component
app.component('svg-icon', SvgIcon)
最后使用 svg
<el-input v-model="loginForm.tenant" auto-complete="off" placeholder="租户编号" type="text">
<template #prefix>
<svg-icon name="user"/>
</template>
</el-input>