### Vue 中优雅使用 SVG
#### 相关文章
在 vue 项目中优雅的使用 Svg - 掘金
https://juejin.cn/post/6844903697999200263 在 vue3+vite 项目中使用 svg - 掘金
https://juejin.cn/post/6932037172178616334通过 vite-plugin-svg-icons 插件封装 SvgIcon 组件 - 掘金
https://juejin.cn/post/7094060278475653128 ---
#### 使用`vite-plugin-svg-icons`插件
##### 安装插件
```shell
// 安装插件
npm install svg-sprite-loader -D
# via yarn
yarn add svg-sprite-loader -D
// 如果报错 需要安装“fast-glob”
yarn add fast-glob -D
```
##### 封装 SvgIcon 组件
```javascript
<template>
<svg :class="svgClass" v-bind="$attrs" :style="{ color: color }">
<use :xlink:href="iconName" />
</svg>
</template>
<script>
import { defineComponent, computed } from "vue";
export default defineComponent({
name: "SvgIcon",
props: {
name: {
type: String,
required: true,
},
color: {
type: String,
default: "#333",
},
},
setup(props) {
const iconName = computed(() => `#icon-${
props.name}`);
const svgClass = computed(() => {
console.log(
props.name, "
props.name");
if (
props.name) {
return `svg-icon icon-${
props.name}`;
}
return "svg-icon";
});
return {
iconName,
svgClass,
};
},
});
</script>
<style scoped>
.svg-icon {
width: 1em;
height: 1em;
fill: currentColor;
vertical-align: middle;
}
</style>
```
##### 配置插件
```javascript
// 配置 vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import { resolve } from 'path'
//
https://vitejs.dev/config/export default defineConfig({
plugins: [
vue(),
createSvgIconsPlugin({
iconDirs: [resolve(process.cwd(), 'src/assets/svg')],
symbolId: 'icon-[dir]-[name]',
})
],
})
// 配置 main.js
import 'virtual:svg-icons-register'
const app = createApp(App);
app
.component("svg-icon", SvgIcon)
.mount('#app');
```
##### 使用插件
```vue
<script setup>
import HelloWorld from "./components/HelloWorld.vue";
import SvgIcon from "./components/SvgIcon.vue";
</script>
<template>
<div>
<a href="
https://vitejs.dev" target="_blank">
<img src="/vite.svg" class="logo" alt="Vite logo" />
</a>
<a href="
https://vuejs.org/" target="_blank">
<img src="./assets/vue.svg" class="logo vue" alt="Vue logo" />
</a>
</div>
<HelloWorld msg="Vite + Vue" />
<SvgIcon name="tree" />
</template>
<style scoped>
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.vue:hover {
filter: drop-shadow(0 0 2em #42b883aa);
}
</style>
```