Vue3 项目优雅使用 SVG
新项目开始准备了,前几天看到了这篇文章:
Vue3!ElementPlus!更加优雅的使用 Icon。
尝试了一下,确实很方便。至于文中关于自动引入的部分,我暂时不打算采用,我认为项目中组件多起来之后,单文件中的引入路径对于寻找源组件是很重要的。
步骤及代码附上:
src
目录下新建 icons
文件夹,放入图标文件 vue.svg
。
javascript
// vite.config.js
import Icons from "unplugin-icons/vite";
import { FileSystemIconLoader } from "unplugin-icons/loaders";
export default defineConfig({
plugins: [
Icons({
compiler: "vue3",
customCollections: {
// 此处为自定义 SVG 图标的分组模块
icons: FileSystemIconLoader("./src/icons"), // icons 模块
// ...
},
}),
],
});
修改图标颜色需要使用 fill,fill-opacity,stroke,stroke-opacity 属性,详细使用看 MDN 填充和边框。
例如:
xml
<rect
fill="purple"
fill-opacity="0.5"
stroke="blue"
stroke-opacity="0.8"
/>
在使用前需要调整 SVG 图标文件的相关属性值为 inherit,调用处传入属性及属性值。
html
<template>
<IconVue fill="pink" />
</template>
<script setup>
import IconVue from "~icons/icons/vue";
</script>
<style>
svg:hover {
fill: lightseagreen;
}
</style>
动态设置 svg 的颜色时,可以将需要控制的属性删除,这样默认为 inherit。如下:
xml
<svg fill="red" xmlns="http://www.w3.org/2000/svg" width="24" height="24">
<path d="M0 0h24v24H0z" />
</svg>
或者使用 currentcolor 关键字:
xml
<svg color="red" xmlns="http://www.w3.org/2000/svg" width="24" height="24">
<path fill="currentcolor" d="M0 0h24v24H0z" />
</svg>