vue项目引入svg图标

1. 安装svg依赖

在vue中首先需要安装可以加载svg的依赖。
npm安装:npm install svg-sprite-loader --save-dev

2. 创建svg文件夹存放svg图标

创建icons文件夹,在icons文件夹下创建svg文件夹存放本地svg图标。

3. vue.config.js 中配置svg图片

vue.config.js代码:

const path = require('path')

function resolve(dir) {
  return path.join(__dirname, dir)
}

module.exports = {
	chainWebpack(config){
		/**
		 * set svg-sprite-loader
		 * svg图标加载 
		 **/ 
		config.module
		  .rule('svg')
		  .exclude.add(resolve('src/icons'))
		  .end()
		  
		config.module
		  .rule('icons') // 定义一个名叫 icons 的规则
		  .test(/\.svg$/) // 设置 icons 的匹配正则
		  .include.add(resolve('src/icons')) // 设置当前规则的作用目录,只在当前目录下才执行当前规则
		  .end()
		  .use('svg-sprite-loader') // 指定一个名叫 svg-sprite-loader 的 loader 配置
		  .loader('svg-sprite-loader') // 该配置使用 svg-sprite-loader 作为处理 loader
		  .options({ // 该 svg-sprite-loader 的配置
		    symbolId: 'icon-[name]'
		  })
		  .end()
	}
}

4. 创建index.js 导入所有svg图标

icons文件夹创建index.js 自动导入所有svg图标。

icons/index.js代码:

import Vue from 'vue'
// svg component
import SvgIcon from '@/components/SvgIcon'

// 全局注册
Vue.component('svg-icon', SvgIcon)

const req = require.context('./svg', false, /\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)

5. main.js中引入icons/index.js

6. 创建SvgIcon公用组件

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>
// doc: https://panjiachen.github.io/vue-element-admin-site/feature/component/svg-icon.html#usage
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>

utils/validate.js代码:

/**
 * @param {string} path
 * @returns {Boolean}
 */
export function isExternal(path) {
  return /^(https?:|mailto:|tel:)/.test(path)
}

全局注册SvgIcon组件:

使用SvgIcon组件: