小知识,大挑战!本文正在参与“程序员必备小知识”创作活动
1.本项目中使用插件进行svg的图标演示,npm下载依赖
npm install svg-sprite-loader --save-dev
2.在vue.config.js文件下的chainWebpack(config)中输入以下的代码
exclude:[resolve('src/icons')]
}
test:/\.svg$/,
loader:'svg-sprite-loader',
include: [resolve('src/icons')],
options: {
symbolid:'icon-[name]'
}
}
3.在src/components目录下添加SvgIcon文件夹,接着在文件夹内创建index.vue
<template>
<div v-if="isExternal" :style="styleExternalIcon" class="svg-external-icon svg-icon" v-on="$listeners" />
<svg v-else :class="svgClass" aria-hidden="true" v-on="$listeners">
<use :xlink:href="iconName" />
</svg>
</template>
<script>
import { isExternal } from '@/utils/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>
```
\4.在src目录中依次创建**icons**文件夹,**svg**文件夹(用来存放下载的svg文件),**index.js**内容如下
```
import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon'// svg component
Vue.component('svg-icon', SvgIcon)
const req = require.context('./svg', false, /.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)
```
5.在main.js中引用
```
import './icons'
```
6.页面使用
```
<svg-icon icon-class="dashboard"></svg-icon>
```
7.注意:在使用阿里图标库使用icon的图标的时候,如果需要更改图标的颜色,需要把svg中的代码的填充色fill删除掉才可以更改当前的颜色,否则无法更改当前icon的颜色。
```