# 基于Iconfont (opens new window) 封装的开箱即用的SVG实现方案

# 功能描述

  将Iconfont 的Symbol使用方式下载到本地,将其中的iconfont.js引入到全局
1

# 目录结构

  |-- src
  |--  |-- assets
  |--  |--  |   |-- fonts
  |--  |--  |   |--  |-- iconfont.js
  |--  |-- components
  |--  |--  |   |-- IconFont
  |--  |--  |   |--  |-- index.vue
  |--  |-- main.js
1
2
3
4
5
6
7
8

# 使用

<template>
  <IconFont
    class="header-icon"
    :icon-class="'icon_clear'"
  />s
</template>
1
2
3
4
5
6

# 实现 (opens new window)

  // main.js
  import '@/assets/fonts'
1
2
  // IconFont/index.vue
  <template>
    <svg
      class="icon"
      aria-hidden="true"
      :class="getClassName"
      @click="handleClick()"
    >
      <filter
        id="drop-shadow"
        xmlns="http://www.w3.org/2000/svg"
      >
        <feGaussianBlur
          in="SourceAlpha"
          stdDeviation="2"
        />
        <feOffset
          dx="1"
          dy="1"
          result="offsetblur"
        />
        <feComponentTransfer>
          <feFuncA
            type="linear"
            slope="0.2"
          />
        </feComponentTransfer>
        <feMerge>
          <feMergeNode />
          <feMergeNode in="SourceGraphic" />
        </feMerge>
      </filter>
      <g
        v-bind="getAttrs()"
      >
        <use :xlink:href="'#' + iconClass" />
      </g>
    </svg>
  </template>

  <script>

  export default {
    name: 'IconFont',
    props: {
      iconClass: {
        type: String,
        default: ''
      },
      shadow: {
        type: Boolean,
        default: false
      },
      verticalCenter: {
        type: Boolean,
        default: false
      }
    },
    computed: {
      getClassName () {
        const className = []
        if (this.verticalCenter) {
          className.push('middle')
        }
        return className
      }
    },
    methods: {
      handleClick () {
        this.$emit('click')
      },
      getAttrs () {
        const attrs = {}
        this.shadow &&
        (attrs.filter = 'url(#drop-shadow)')
        return attrs
      }
    }
  }
  </script>

  <style lang="scss" scoped>
  .icon {
    width: 1em; height: 1em;
    vertical-align: -0.15em;
    fill: currentColor;
    overflow: hidden;
    &.middle {
      vertical-align: middle;
    }
  }
  </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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
最后更新时间: 12/13/2020, 3:55:50 PM