技术规范

@vue/cli 4.5.13 (typescript开发模式)

node v14.16.0

svg-sprite-loader

安装svg-sprite-loader

npm i svg-sprite-loader --save-dev
在项目根目录下创建vue.config.js并加入以下内容:
module.exports = {
  /**
   * your own code
   */
  chainWebpack: config => {
    /**
     * your own code
     */
    const svgRule = config.module.rule("svg");
    // 清除已有的所有 loader。
    // 如果你不这样做,接下来的 loader 会附加在该规则现有的 loader 之后。
    svgRule.uses.clear();
    // 添加要替换的 loader
    svgRule
      .test(/\.svg$/)
      .use("svg-sprite-loader")
      .loader("svg-sprite-loader")
      .options({
        symbolId: "icon-[name]"
      })
      .end();
    /**
     * your own code
     */
  }
  /**
   * your own code
   */
};
创建一个通用模板便于调用:
<!-- SvgIcon Component -->
<template>
  <svg :class="svgClass" aria-hidden="true">
    <use :xlink:href="iconName"/>
  </svg>
</template>

<script lang="ts">
import { Component, Prop, Vue } from "vue-property-decorator";

@Component
export default class SvgIcon extends Vue {
  @Prop() iconClass!: string
  @Prop() className!: string

  private get iconName() {
    return `#icon-${this.iconClass}`;
  }

  private get svgClass() {
    if (this.className) {
      return `svg-icon ${this.className}`;
    } else {
      return "svg-icon";
    }
  }
}
</script>

<style scoped lang="scss">
.svg-icon {
  // 如果父级元素配置了overflow,width和height配置为100%时会导致父级元素出现滚动条。暂不清楚原因,目前解决方案是都配置为99%。
  width: 99%;
  height: 99%;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
</style>
使用svg:
<template>
  <div>
    <!-- your own code -->
    <!-- note: icon class is svg file name -->
    <svg-icon iconClass="no-video1"></svg-icon>
    <!-- your own code -->
  </div>
</template>

<!-- reference basic code -->