SVG(即“可缩放矢量图形”)图标在诸多场合下,往往胜过一般的位图标记(例如PNG、JPG、GIF等)。
- 体积微:SVG乃矢量图像格式,以一连串数学函数及坐标点来描绘图像,使得SVG文件体积往往甚于位图更小。
- 可无穷缩放:由于SVG为矢量图,故可在图像质量不损失的环境下进行无限缩放,此对于开发高DPI(即“屏幕像素密度”)显示装置,例如Retina屏的网页应用,大有益。
- 易于更改:SVG另一优点在于,其实为基于XML,故可方便地由CSS及Javascript进行更改及操作。
- 应用广泛:除图标外,SVG亦常用于复杂的图表、插图、动画等。
然而,SVG并非在所有情形下皆为最佳选择。对于一些复杂度较高及色彩丰富的图像,例如照片,使用位图可能更为恰当。因此,在每个具体的项目中,皆需依据实际需求而决定使用何者。
具体步骤
一、安装
npm i svg-sprite-loader --save
二、在compontents文件夹中,新建文件夹 SvgIcon, 在文件夹下新建文件 index.vue
SvgIcon/index.vue
<template>
<svg :class="svgClass" aria-hidden="true" v-on="$listeners">
<use :xlink:href="iconName" />
</svg>
</template>
<script>
export default {
name: 'SvgIcon',
props: {
iconClass: {
type: String,
required: true
},
className: {
type: String,
default: ''
}
},
computed: {
iconName () {
return `#icon-${this.iconClass}`
},
svgClass () {
if (this.className) {
return 'svg-icon ' + this.className
} else {
return 'svg-icon'
}
},
styleExternalIcon () {
return {
mask: `url(${this.iconClass}) no-repeat 50% 50%`,
'-webkit-mask': `url(${this.iconClass}) no-repeat 50% 50%`
}
}
}
}
</script>
<style scoped>
.svg-icon {
width: 1.5em;
height: 1.5em;
vertical-align: -0.2em;
fill: currentColor;
overflow: hidden;
}
.svg-external-icon {
background-color: currentColor;
mask-size: cover!important;
display: inline-block;
}
</style>
三、src 目录下新加目录icons , 新增index.js文件 src/icons/index.js
四、 在main.js 中引用
import './icons'
五、项目配置 vue.config.js 文件新增代码片段
chainWebpack: (config) => {
const entry = config.entry("app");
entry.add("babel-polyfill").end();
entry.add("classlist-polyfill").end();
config.module.rule("svg").exclude.add(resolve("src/icons")).end();
config.module
.rule("icons")
.test(/\.svg$/)
.include.add(resolve("src/icons"))
.end()
.use("svg-sprite-loader")
.loader("svg-sprite-loader")
.options({
symbolId: "icon-[name]",
})
.end();
},
六、 在页面中引用
<SvgIcon iconClass="like"></SvgIcon>