Skip to content
On this page

svg-icon

目前业界统一用svg-sprite-loader实现 svg-icon 方案,事实上很多整合框架包含了这个方案。具体如下,在 Vue 2 和 Vue 3 下测试通过:

实施方案

1. 安装 svg-sprite-loader

sh
yarn add -D svg-sprite-loader

2. 配置 vue.config.js

js
const path = require('path');

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

module.exports = {
  chainWebpack(config) {
    config.module.rule('svg').exclude.add(resolve('src/assets/icons')).end();
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/assets/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]',
      })
      .end();
  },
};

3. 创建 @/components/SvgIcon/index.vue

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>
export default {
  name: 'SvgIcon',
  props: {
    iconClass: {
      type: String,
      required: true,
    },
    className: {
      type: String,
      default: '',
    },
  },
  computed: {
    isExternal() {
      return /^(https?:|mailto:|tel:)/.test(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>

4. 创建 @/assets/icons/index.js

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

同时创建@/assets/icons/svg/,准备存放各种 svg 图标。

5. 修改 main.js

Vue 2:

js
import SvgIcon from '@/components/SvgIcon';
Vue.component('svg-icon', SvgIcon);
import './assets/icons';

Vue 3:

js
import SvgIcon from '@/components/SvgIcon';
import './assets/icons';

// 在 .mount('#app') 之前注册组件
createApp(App).use(store).use(router).component('svg-icon', SvgIcon).mount('#app');

使用方式

  1. https://www.iconfont.cn下载 svg 图标到@/assets/icons/svg/

  2. 使用<svg-icon icon-class="文件名" />调用 svg-icon,其中icon-class的值是文件名。

  3. 使用<svg-icon icon-class="http://www.xxx.com/ooo.svg" />则可以使用网络 svg 资源。

  4. 给组件加上颜色样式可以给图标更改颜色,加font-size样式则可以控制大小。

可浏览所有图标的组件

1. 创建 @/components/IconSelect/index.vue

它有几个方法可以调用,也可以emit一个selected事件,不具体解释。

vue
<template>
  <div class="icon-body">
    <el-input
      v-model="name"
      style="position: relative;"
      clearable
      placeholder="请输入图标名称"
      @clear="filterIcons"
      @input.native="filterIcons"
    >
      <i slot="suffix" class="el-icon-search el-input__icon" />
    </el-input>
    <div class="icon-list">
      <div v-for="(item, index) in iconList" :key="index" @click="selectedIcon(item)">
        <svg-icon :icon-class="item" style="height: 30px;width: 16px;" />
        <span>{{ item }}</span>
      </div>
    </div>
  </div>
</template>

<script>
import icons from './requireIcons';
export default {
  name: 'IconSelect',
  data() {
    return {
      name: '',
      iconList: icons,
    };
  },
  methods: {
    filterIcons() {
      this.iconList = icons;
      if (this.name) {
        this.iconList = this.iconList.filter((item) => item.includes(this.name));
      }
    },
    selectedIcon(name) {
      this.$emit('selected', name);
      document.body.click();
    },
    reset() {
      this.name = '';
      this.iconList = icons;
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.icon-body {
  width: 100%;
  padding: 10px;
  .icon-list {
    height: 200px;
    overflow-y: scroll;
    div {
      height: 30px;
      line-height: 30px;
      margin-bottom: -5px;
      cursor: pointer;
      width: 33%;
      float: left;
    }
    span {
      display: inline-block;
      vertical-align: -0.15em;
      fill: currentColor;
      overflow: hidden;
    }
  }
}
</style>

2. 创建 @/components/IconSelect/requireIcons.js

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

const re = /\.\/(.*)\.svg/;

const icons = requireAll(req).map((i) => {
  return i.match(re)[1];
});

export default icons;

杨亮的前端解决方案