(@_@;)我是程序猿,我编程,我快乐,知识改变命运,技术成就梦想   oh yeah!合作VX "w6668263" 联系Email:ye583025823@126.com

利用svg-sprite-loader svgo-loader 自动化创建vue svg组件,支持改变颜色。

 首先还是安装依赖包:

 

npm install svg-sprite-loader svgo-loader --D

 

 

 

vue.config.js中的webpack配置

 

const { resolve } = require('path')
module.exports = {
  chainWebpack: config => {
    config.module
      .rule('svg')
      .exclude.add(resolve('src/assets/icons/'))
      .end()
    config.module
      .rule('svg-sprite')
      .test(/\.svg$/)
      // 处理svg目录
      .include.add(resolve('src/assets/icons/'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()
      .before('svg-sprite-loader')
      .use('svgo-loader')
      .loader('svgo-loader')
      .options({
        plugins: [
          {
            name: 'removeAttrs',
            params: {
              attrs: '(fill|stroke)'
            }
          },
          {
            name: 'removeTitle'
          }
        ]
      })
      .end()
  }
}

 

 

创建vue组件SvgIcon.vue

 

<template>
  <svg class="svg-icon" :class="{ 'icon-spin': spin }" aria-hidden="true" v-on="$listeners">
    <use :xlink:href="`#icon-${iconName}`"/>
  </svg>
</template>

<script>

export default {
  name: 'SvgIcon',
  props: {
    iconName: {
      type: String,
      required: true
    },
    spin: {
      type: Boolean,
      default: false
    }
  }
}
</script>

<style scoped>
.svg-icon {
  stroke: currentColor;
  fill: currentColor;
  cursor: pointer;
  margin-bottom: 0.125em;
  vertical-align: middle;
  height: 1em;
  width: 1em;
}
.svg-icon .icon-spin {
  animation: icon-spin 2s infinite linear;
}
@keyframes icon-spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(359deg);
  }
}
</style>

 

 

注册组件,我的是在main.js中全局注册组件

 

import Vue from 'vue'

// svg图标
import SvgIcon from './components/svgIcon/SvgIcon'
Vue.component('svg-icon', SvgIcon)
// 把路径/assets/icons/下面的svg文件全局注册
const svgIcons = require.context('@/assets/icons/', false, /\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(svgIcons)

 

 

测试组件:在文件夹src/assets/icons/下面放一张icon-2X2.svg

下面是一个Test.vue测试组件

 

<template>
    <svg-icon class="icons-button" icon-name="icon-2X2" />
</template>
<script>
    export default {
        name: 'Test'
    }
</script>
<style scoped>
.icons-button {
    color: darkgreen;
    //cursor: pointer;

    &:hover {
        color: coral;
    }
}
</style>

 

posted on 2022-03-21 19:48  一个草率的龙果果  阅读(611)  评论(0编辑  收藏  举报

导航