[svg-icon] vueプロジェクト導入後、useタグが0になる問題は解決されました

以前にもこのバグに遭遇しましたが、解決したときは記録されていませんでした。

しかし、良い記憶力は悪いペンほど良くはありません。今回もまた遭遇し、バグを再度確認するのに 1 時間以上かかりました

svgインポートvueプロジェクト、svg-sprite-loaderに依存する必要があります

npm install  svg-sprite-loader

vue.config.js内

chainWebpack(config) {
    
    
    config.plugins.delete("preload"); // TODO: need test
    config.plugins.delete("prefetch"); // TODO: need test

    // set svg-sprite-loader
    config.module
      .rule("svg")
      .exclude.add(resolve("src/assets/icons"))
      // .add(resolve("src/assets/icons"))//如果还有其他文件夹下有,就add增加
      .end();
    config.module
      .rule("icons")
      .test(/\.svg$/)
      .include.add(resolve("src/assets/icons"))
      // .add(resolve("src/assets/icons"))
      .end()
      .use("svg-sprite-loader")
      .loader("svg-sprite-loader")
      .options({
    
     symbolId: "icon-[name]" })
      .end();

  },


ここに画像の説明を挿入
Index.js に対応するアセットの下に新しいアイコン フォルダーを作成します。

import Vue from "vue";
import SvgIcon from "@/components/SvgIcon"; // svg component

// register globally
Vue.component("svg-icon", SvgIcon);

const req = require.context("./svg", true, /\.svg$/);
const requireAll = (requireContext) =>
  requireContext.keys().map(requireContext);
requireAll(req);


ここに画像の説明を挿入
Index.vue に対応するコンポーネントフォルダーの下に新しい SvgIcon フォルダーを作成します。

<template>
  <svg :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: {
    
    

    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>

main.js でグローバルにマウントする

import "@/assets/icons"; // icon
import "@/components/SvgIcon"; // 自定义组件引入

特定のページで使用する

            <svg-icon icon-class="logo" />

use タグが 0 である主な理由は、vue.config.js に対応する svg-sprite-loader が設定されていないことです。

備考: svg タグは通常、ui によって直接指定されます。自分で定義する必要がある場合は、新しいテキスト ドキュメントを作成し、内容をコピーし、サフィックスを .svg に変更します。

おすすめ

転載: blog.csdn.net/weixin_49668076/article/details/130542064