项目添加svgIcon

4/5/2020 Vue技巧

# 项目添加svgIcon

  1. 安装
npm i svg-sprite-loader  -S
1
  1. vue.config.js 中的 chainWebpack 修改
const path = require('path')
function resolve(dir) {
  return path.join(__dirname, './', dir)
}

...

module.exports = {
  chainWebpack(config) {
    // set svg-sprite-loader
    config.module
      .rule('svg')
      .exclude.add(resolve('src/icons'))
      .end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
  1. src下新建icons文件夹放svg文件

  2. 编写svgIcon 组件,components下新建SvgIcon.vue

<template>
  <svg :class="svgClass" aria-hidden="true" 

  // /* 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: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
  1. main.js中
import SvgIcon from '@/components/SvgIcon'

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

requireAll(req)
Vue.component('svg-icon',SvgIcon) // 全局注册
1
2
3
4
5
6
7
  1. 使用
<svg-icon
  icon-class="ch"
  style="width: 2em; height: 2em;vertical-align:middle"
></svg-icon>
1
2
3
4

svg图标封装组件 (opens new window)vue-element-admin使用svg图标 (opens new window)

Last Updated: 12/30/2022, 2:33:12 PM