环境:
- vue-cli 3.0
- vue @2.x
安装插件 svg-sprite-loader
$ npm i svg-sprite-loader -D
webpack配置
在根目录的vue.config.js里添加如下代码:
module.exports = {
chainWebpack(config) {
// set svg-sprite-loader
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组件
在src/components下创建组件SvgIcon/index.vue,组件内容如下:
<template>
<div
:style="styleExternalIcon"
class="svg-external-icon svg-icon"
v-if="isExternal"
v-on="$listeners"
/>
<svg :class="svgClass" aria-hidden="true" v-else v-on="$listeners">
<use :xlink:href="iconName" />
</svg>
</template>
<script>
import { isExternal } from '@/util/validate';
export default {
name: 'SvgIcon',
props: {
iconClass: {
type: String,
required: true,
},
className: {
type: String,
default: '',
},
},
computed: {
isExternal() {
return isExternal(this.iconClass);
},
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: 1em;
height: 1em;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
.svg-external-icon {
background-color: currentColor;
mask-size: cover !important;
display: inline-block;
}
</style>
这里还缺一个validate.js,创建文件src/util/validate.js
export function isExternal(path) {
return /^(https?:|mailto:|tel:)/.test(path);
}
创建icons目录
在src下创建icons目录,目录结构如下:
icons
|_ svg
|_ xxx.svg
|_ index.js
|_ svgo.yml
index.js的内容:
import Vue from 'vue';
import SvgIcon from '@/components/Common/SvgIcon/index.vue'; // svg component
// register globally
Vue.component('svg-icon', SvgIcon);
const req = require.context('./svg', false, /\.svg$/);
const requireAll = requireContext => requireContext.keys().map(requireContext);
requireAll(req);
svgo.yml的内容:
# replace default config
# multipass: true
# full: true
plugins:
# - name
#
# or:
# - name: false
# - name: true
#
# or:
# - name:
# param1: 1
# param2: 2
- removeAttrs:
attrs:
- 'fill'
- 'fill-rule'
在main.js里导入icons
import './icons'; // icon
使用svg-icon
<svg-icon icon-class="count" class-name="my-icon" />
- icon-class 是图标的文件名
- class-name 是自定义的class名
注:修改了vue.config.js要重新运行项目才有效