[Vuejs] svg-sprite-loader实现加载svg自定义组件

1、安装 svg-sprite-loader

npm install svg-sprite-loader -D

或者

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

2、将所有svg图片放到assets/svg下,以此为例,修改文件 build/webpack.base.conf.js

找到代码:

{
  test: /.(png|jpe?g|gif|svg)(?.*)?$/,
  loader: 'url-loader',
  options: {
    limit: 10000,
    name: utils.assetsPath('img/[name].[hash:7].[ext]')
  }
},

增加一行 

exclude: [resolve("src/assets/svg")],

意思是用url-loader加载的时候过滤掉文件夹 src/assets/svg 下面的文件

{
  test: /.(png|jpe?g|gif|svg)(?.*)?$/,
  exclude: [resolve("src/assets/svg")],
  loader: 'url-loader',
  options: {
    limit: 10000,
    name: utils.assetsPath('img/[name].[hash:7].[ext]')
  }
},

同时在后面增加一条规则

{
  test: /.svg$/,
  loader: "svg-sprite-loader",
  include: [resolve("src/assets/svg")],
  options: {
    symbolId: "[name]"
  }
}

3、自定义SvgIcon组件

在components新建 SvgIcon.vue

<template>
  <svg :class="svgClass" :style="style" aria-hidden="true">
    <use :xlink:href="`#${name}`"></use>
  </svg>
</template>

<script type="text/ecmascript-6">
export default {
  name: 'svg-icon',
  props: {
    name: {
      type: String,
      required: true
    },
    className: {
      type: String
    },
     {
      type: String,
      default: '5vw'
    },
    height: {
      type: String,
      default: '5vw'
    }
  },
  data () {
    return {
      style: {
         this.width,
        height: this.height
      }
    }
  },
  computed: {
    svgClass () {
      if (this.className) {
        return 'svg-icon ' + this.className
      } else {
        return 'svg-icon'
      }
    }
  }
}
</script>

<style>
.svg-icon {
  width: 5vw;
  height: 5vw;
  fill: currentColor;
  overflow: hidden;
}
</style>

其中绑定了class和style,在用这个组件的时候可以直接设置宽度和高度以及类名,额外的属性可以自己扩展。

4、创建svg.js用于注册SvgIcon组件和批量引入svg图片,我创建在src/utils/svg.js

import Vue from 'vue'
import SvgIcon from '../components/SvgIcon.vue'

Vue.component('svg-icon', SvgIcon)

// 引入所有svg
const requireAll = requireContext => requireContext.keys().map(requireContext)
const req = require.context('../assets/svg', false, /.svg$/)
// const iconMap = requireAll(req)
// console.log(iconMap)
requireAll(req)

5、用法

<svg-icon name="icon-pc" width="12vw" height="12vw"></svg-icon>

name值即为svg图片名称,如上icon-pc,即为icon-pc.svg

原文地址:https://www.cnblogs.com/frost-yen/p/9608711.html