一个生成 svg 图标组件的工具: vue-svgicon (vue 2.x)
这是一个生成 vue2.x 的 svg 图标组件的工具(包含一个插件)
重要特性
- svg 图标压缩
- 多颜色方案
- 可以使用渐变和动画
- 可以旋转上、下、左、右四个方向
安装
# 全局安装
npm install vue-svgicon -g
# 安装到项目目录
npm install vue-svgicon --save-dev
使用
第一步:生成图标组件
使用命令行
# generate svg icon components
vsvg -s /path/to/svg/source -t /path/for/generated/components
建议使用 npm scripts
{
"scripts": {
"svg": "vsvg -s ./static/svg/src -t ./src/icons"
}
}
# bash
npm run svg
第二步:使用生成的图标组件
先注册插件
// main.js
import Vue from 'vue'
import App from './App.vue'
import svgicon from 'vue-svgicon'
// Default tag name is 'svgicon'
Vue.use(svgicon, {
tagName: 'svgicon'
})
new Vue({
el: '#app',
render: h => h(App)
})
在组件中使用图标
<!-- App.vue -->
<template>
<div id="app">
<p>
<svgicon icon="vue" width="200" height="200" color="#42b983 #35495e"></svgicon>
</p>
</div>
</template>
<script>
// 根据需要引入图标
import 'icons/vue'
export default {
name: 'app',
data () {
return {
msg: 'Welcome to Your Vue.js App',
}
}
}
</script>
如果觉得一个个引入图标麻烦的话,可以将图标一次性引入
import 'icons'
属性
icon
图标名称
<svgicon icon="vue"></svgicon>
方向
图标旋转的方向, 默认值是 right
<svgicon icon="arrow" width="50" height="50" dir="left"></svgicon>
<svgicon icon="arrow" width="50" height="50" dir="up"></svgicon>
<svgicon icon="arrow" width="50" height="50"></svgicon>
<svgicon icon="arrow" width="50" height="50" dir="down"></svgicon>
fill
是否填充 path/shape, 默认值是 true
<svgicon icon="arrow" width="50" height="50"></svgicon>
<svgicon icon="arrow" width="50" height="50" :fill="false"></svgicon>
width / height
图标大小。 默认值是 16px / 16px. 默认单位是 px
<svgicon icon="arrow" width="50" height="50"></svgicon>
<svgicon icon="arrow" width="10em" height="10em"></svgicon>
Color
图标的颜色。默认继承父元素的颜色
<p style="color: darkorange">
<svgicon icon="arrow" width="50" height="50"></svgicon>
<svgicon icon="arrow" width="50" height="50" color="red"></svgicon>
<svgicon icon="arrow" width="50" height="50" color="green"></svgicon>
<svgicon icon="arrow" width="50" height="50" color="blue"></svgicon>
</p>
如果图标有多个 path/shape, 可以定义多个颜色。定义的顺序是根据 path/shape 的位置。
<svgicon icon="vue" width="100" height="100" color="#42b983 #35495e"></svgicon>
可以使用 css 定义颜色
<svgicon class="vue-icon" icon="vue" width="100" height="100"></svgicon>
.vue-icon path[pid="0"] {
fill: #42b983
}
.vue-icon path[pid="1"] {
fill: #35495e
}
不能在 scoped 区块那里定义颜色,因为 path/shape 不在模板里面的,然后 scoped 生成的样式不能匹配
使用渐变
<template>
<svg>
<defs>
<linearGradient id="gradient-1" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stop-color="#57f0c2"/>
<stop offset="95%" stop-color="#147d58"/>
</linearGradient>
<linearGradient id="gradient-2" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stop-color="#7295c2"/>
<stop offset="95%" stop-color="#252e3d"/>
</linearGradient>
</defs>
</svg>
<svgicon icon="vue" width="15rem" height="15rem" color="url(#gradient-1) url(#gradient-2)"></svgicon>
</template>
另外
写这个工具(插件)的灵感来自于 vue-awesome。 发布之后,发现了另外一个有点类似的库:vue-svg-icon。如果大家有什么建议,欢迎提 issue。