原文:https://www.jianshu.com/p/d1a0cb8b8866
在vue项目中使用svg,并能根据需要修改svg大小颜色等样式:https://blog.csdn.net/weixin_42204698/java/article/details/93751906
阿里图标iconfont彩色图标显示黑白色的解决方法:https://www.w3h5.com/post/402.html
1、安装svg-sprite-loader。
npm install svg-sprite-loader --save-dev
2、/src/components 创建 SvgIcon.vue
<template><svg :class="svgClass" aria-hidden="true"><use :xlink:href="iconName" /></svg></template><script>/*** 使用栗子* <svg-icon icon-class="set"></svg-icon>*/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'}}}}</script><style scoped>.svg-icon {width: 1em;height: 1em;vertical-align: -0.15em;fill: currentColor;overflow: hidden;}</style>

目录结构
3、src/icons/index.js
import Vue from 'vue'import SvgIcon from '@/components/SvgIcon' // svg组件// 注册全局组件Vue.component('svg-icon', SvgIcon)const requireAll = reqireContext => reqireContext.keys().map(reqireContext)const req = require.context('./svg', false, /\.svg$/)requireAll(req)
4、src/icons/svg 放svg即可(最好使用iconfont上的svg)
5、vue-config.js配置
const path = require('path')function resolve (dir) {return path.join(__dirname, './', dir)}module.exports = {configureWebpack: config => {},chainWebpack: config => {// svg loaderconst svgRule = config.module.rule('svg') // 找到svg-loadersvgRule.uses.clear() // 清除已有的loader, 如果不这样做会添加在此loader之后svgRule.exclude.add(/node_modules/) // 正则匹配排除node_modules目录svgRule // 添加svg新的loader处理.test(/\.svg$/).use('svg-sprite-loader').loader('svg-sprite-loader').options({symbolId: 'icon-[name]'})// 修改images loader 添加svg处理const imagesRule = config.module.rule('images')imagesRule.exclude.add(resolve('src/icons'))config.module.rule('images').test(/\.(png|jpe?g|gif|svg)(\?.*)?$/)},}}
6、使用
index.vue
<svg-icon icon-class="eye"></svg-icon>
ps: 修改svg颜色可使用color:red;或者fill:red;
作者:取个帅气的名字真好
链接:https://www.jianshu.com/p/d1a0cb8b8866
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
