原文: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

    1. npm install svg-sprite-loader --save-dev

    2、/src/components 创建 SvgIcon.vue

    1. <template>
    2. <svg :class="svgClass" aria-hidden="true">
    3. <use :xlink:href="iconName" />
    4. </svg>
    5. </template>
    6. <script>
    7. /**
    8. * 使用栗子
    9. * <svg-icon icon-class="set"></svg-icon>
    10. */
    11. export default {
    12. name: 'SvgIcon',
    13. props: {
    14. iconClass: {
    15. type: String,
    16. required: true
    17. },
    18. className: {
    19. type: String,
    20. default: ''
    21. }
    22. },
    23. computed: {
    24. iconName() {
    25. return `#icon-${this.iconClass}`
    26. },
    27. svgClass() {
    28. if (this.className) {
    29. return 'svg-icon ' + this.className
    30. } else {
    31. return 'svg-icon'
    32. }
    33. }
    34. }
    35. }
    36. </script>
    37. <style scoped>
    38. .svg-icon {
    39. width: 1em;
    40. height: 1em;
    41. vertical-align: -0.15em;
    42. fill: currentColor;
    43. overflow: hidden;
    44. }
    45. </style>

    svg组件 - 图1
    目录结构
    3、src/icons/index.js

    1. import Vue from 'vue'
    2. import SvgIcon from '@/components/SvgIcon' // svg组件
    3. // 注册全局组件
    4. Vue.component('svg-icon', SvgIcon)
    5. const requireAll = reqireContext => reqireContext.keys().map(reqireContext)
    6. const req = require.context('./svg', false, /\.svg$/)
    7. requireAll(req)

    4、src/icons/svg 放svg即可(最好使用iconfont上的svg)
    5、vue-config.js配置

    1. const path = require('path')
    2. function resolve (dir) {
    3. return path.join(__dirname, './', dir)
    4. }
    5. module.exports = {
    6. configureWebpack: config => {
    7. },
    8. chainWebpack: config => {
    9. // svg loader
    10. const svgRule = config.module.rule('svg') // 找到svg-loader
    11. svgRule.uses.clear() // 清除已有的loader, 如果不这样做会添加在此loader之后
    12. svgRule.exclude.add(/node_modules/) // 正则匹配排除node_modules目录
    13. svgRule // 添加svg新的loader处理
    14. .test(/\.svg$/)
    15. .use('svg-sprite-loader')
    16. .loader('svg-sprite-loader')
    17. .options({
    18. symbolId: 'icon-[name]'
    19. })
    20. // 修改images loader 添加svg处理
    21. const imagesRule = config.module.rule('images')
    22. imagesRule.exclude.add(resolve('src/icons'))
    23. config.module
    24. .rule('images')
    25. .test(/\.(png|jpe?g|gif|svg)(\?.*)?$/)
    26. },
    27. }
    28. }

    6、使用
    index.vue

    1. <svg-icon icon-class="eye"></svg-icon>

    ps: 修改svg颜色可使用color:red;或者fill:red;

    作者:取个帅气的名字真好
    链接:https://www.jianshu.com/p/d1a0cb8b8866
    来源:简书
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。