vue全局使用svg

1、安装依赖

 npm install svg-sprite-loader

2、配置选项
vue.config.jschainWebpack里配置下面代码
解释:config.module.rule是一个方法,用来获取某个对象的规则。.exclude.add(文件a)是往禁用组添加文件a,就是对文件a进行禁用。.test(/.svg$/)是匹配到.svg结尾的文件

config.module
			.rule('svg')
			.exclude.add(resolve('src/icons')) //对应下面配置svg的路径
			.end();

		config.module
			.rule('icons')
			.test(/\.svg$/)
			.include.add(resolve('src/icons')) //对应下面配置svg的路径
			.end()
			.use('svg-sprite-loader')
			.loader('svg-sprite-loader')
			.options({
    
    
				symbolId: 'icon-[name]'
			});

3、定义组件
把svg封装成组件,我们就可以以组件的形式调用svg图片。在components下面写组件。
![在这里插入图片描述](https://img-blog.csdnimg.cn/32965f01cca749f19275783e8959b175.png

componnets/svgIcon/index.vue:

<template>
  <svg :class="svgClass" aria-hidden="true" v-on="$listeners">
    <use :xlink:href="iconName"/>
  </svg>
</template>

<script>
  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: 10em;
    height: 10em;
    vertical-align: -0.15em;
    fill: currentColor;
    overflow: hidden;
  }
</style>

4、存储图片,全局注册
创建文件目录,放置svg图片
我把svg图片放在src/icons/svg文件夹下,然后再将svgIcon注册为全局组件
在这里插入图片描述
src/icons/index.js:

import Vue from 'vue'
import SvgIcon from '@/components/svgIcon/index'// 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)

5、全局引入
在mian.js中引入注册文件

import './icons'

6、使用
例如有一张图片rain.svg,路径是icons/svg/rain.svg,然后直接用名称就可以调用。这里的className是自定义样式


//<svg-icon icon-class="图片名" className="样式类"></svg-icon>
<svg-icon icon-class="rain" className="iconBig"></svg-icon>

猜你喜欢

转载自blog.csdn.net/qq_43840793/article/details/130152299