VUE-CLI3使用SVG

  • プラグインをインストールするには、コマンドを実行し npm install svg-sprite-loader --save-dev
  • ではvue.config.js真ん中、設定を追加

      module.exports = {
          ...
          chainWebpack: config => {
              // 一个规则里的 基础Loader
              // svg是个基础loader
              const svgRule = config.module.rule("svg");
    
              // 清除已有的所有 loader。
              // 如果你不这样做,接下来的 loader 会附加在该规则现有的 loader 之后。
              svgRule.uses.clear();
    
              // 添加要替换的 loader
              svgRule
              .use("svg-sprite-loader")
              .loader("svg-sprite-loader")
              .options({
                  symbolId: "icon-[name]"
              });
          },
          ...
      }
  • 公共SVG VUEコンポーネントを作成します。svgIcon.vue

      <template>
      <svg :class="svgClass" aria-hidden="true">
          <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 lang="scss" scoped>
      .svg-icon {
          width: 1em;
          height: 1em;
          vertical-align: -0.15em;
          fill: currentColor;
          overflow: hidden;
      }
      </style>
  • 新しいsvg-iconフォルダは、フォルダが含まれているsvgindex.js、それぞれ、元の文書と導入SVGコードを。index.js言います:

      import Vue from 'vue'
      import svgIcon from '@/components/svgIcon'
    
      Vue.component('svg-icon', svgIcon)   // 挂载在全局
    
      const requireAll = requireContext => requireContext.keys().map(requireContext)
      const req = require.context('./svg', false, /\.svg$/)
      requireAll(req);
  • 使用<svg-icon icon-class="svgname" />// svgnameをしなければならない/svg-icon/svg/同じSVGファイルで指定されました。

おすすめ

転載: www.cnblogs.com/Tianbao/p/11817071.html