<!-- iconfont应用 --><i class="iconfont icon-user" style="color: #f00;font-size: 64px;"></i><!-- VS --><!-- 封装svg应用 --><svg-icon icon="user" color="#f00" :size="64" />
同时,在 flex 布局大行其道的明天,icons 与文字的对其,曾经不存在任何问题。
SVG 还有一个 iconfont 做不到的个性:多色彩图标。这足以满足一些对非凡图标显示的场景。
平滑适度指南
- Vite + Vue 3
首先,在 src
目录下创立 icons
目录,用以搁置收集的单体 SVG
文件。
接着,装置 vite-plugin-svg-icons
这个依赖:
$ pnpm add vite-plugin-svg-icons -D
改一点 Vite
的配置:
// vite.config.jsimport { defineConfig } from 'vite'import { resolve } from 'path'import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'export default defineConfig({ ..., plugins:[ ..., createSvgIconsPlugin({ iconDirs: [resolve(process.cwd(), 'src/icons')], symbolId: 'i-[name]', customDomId: '__svg__icons__dom__', }) ]})
在 main.js
中注入生成 svg symbols
的办法:
// src/main.jsimport 'virtual:svg-icons-register'
在做完以上各个步骤之后,body 中就会多出一个 svg 元素,外面就是 icons 目录下单体文件所对应的 symbols 。
而后,咱们就能够创立 SvgIcon
组件了:
<!-- src/components/SvgIcon.vue --><template> <svg class="icon" :width="size" :height="size" aria-hidden="true"> <use :xlink:href="`#i-${icon}`" :fill="color" /> </svg></template><script setup>defineProps({ icon: { type: String, required: true }, color: { type: String, default: '#fff' }, size: { type: Number, default: 32 }})</script>
能够在 main.js
中进行全局注册:
// src/main.jsimport {createApp} form 'vue'import App from '@/App.vue'import SvgIcon from '@components/SvgIcon.vue'const app = createApp(App)app.component('SvgIcon', SvgIcon)
组件的应用:
<svg-icon icon="user" color="#f00" :size="64" /><!-- icon 属性对应 icons 目录下 svg 文件名:例如,上述例子中 user 对应 icons/user.svg -->
后续如果 icons 须要裁减,只须要把新增的 svg 文件间接增加进 icons 目录即可。
- 小程序
因为小程序的 wxml 不反对 SVG 间接渲染,只能通过 image
的 src 进行显示。此种显示的形式,最大的问题是如何更改 icon 的色彩不能够更改,所以须要对文件进行解决。
实现思路:svg 文件 => binary 字符串 => 替换 fill 属性
。
具体的实现形式:
<!-- components/SvgIcon/index.wxml --><view class="icon-wrapper" style="width:{{size}}rpx;height:{{size}}rpx;"> <image class="icon" src="{{iconPath}}" mode="aspectFit"/></view>
/* components/SvIcon/index.wxss */.icon-wrapper { display: flex; align-items: center; justify-content: center; overflow: hidden;}.icon { width: 100%; height: 100%;}
// components/SvIcon/index.jsComponent({ properties: { icon: { type: String, required: true }, color: { type: String, value: '#f00' }, size: { type: Number, value: 32 } }, data: { base: 'icons/', iconPath: '' }, lifetimes: { attached() { const { base } = this.data const { icon, color } = this.properties const filePath = `${base}${icon}.svg` const svgBinary = wx.getFileSystemManager().readFileSync(filePath, 'binary') const svgBase64 = `data:image/svg+xml,${encodeURIComponent(svgBinary.replace(/(#[a-fA-F0-9]{6})|(#[a-fA-F0-9]{3})/g, color))}` this.setData({ iconPath: svgBase64 }) } }})
而后,在 app.json
进行全局注册:
{ ..., "usingComponents": { "svg-icon": "./components/SvgIcon/index" }}
组件应用:
<svg-icon icon="user" color="#f00" size="{{64}}" />
(本文完)
本文由博客一文多发平台 OpenWrite 公布!