添加依赖 

npm install svg-sprite-loader -D
# 或
yarn add svg-sprite-loader -D

打开vue.config.js


module.exports = {
  chainWebpack: config => {
    //svg
    const svgRule = config.module.rule("svg");
    svgRule.uses.clear();
    svgRule
      .test(/\.svg$/)
      .include.add(path.resolve(__dirname, "src/assets/icons"))
      .end()
      .use("svg-sprite-loader")
      .loader("svg-sprite-loader")
      .options({
        symbolId: "icon-[name]"
      });
    const fileRule = config.module.rule("file");
    fileRule.uses.clear();
    fileRule
      .test(/\.svg$/)
      .exclude.add(path.resolve(__dirname, "src/assets/icons"))
      .end()
      .use("file-loader")
      .loader("file-loader");
  }
};

在assets目录下新建icons,存放图标

 新建样式和组件

  style.less

.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}

 SvgIcon.tsx 

如果使用模板,转换成模板即可

import { defineComponent, computed } from "vue";
import "./style.less";
export default defineComponent({
  name: "SvgIcon",
  props: {
    id: { type: [String, Number] },
    class: { type: String },
    icon: { type: String, required: true }
  },
  setup(props) {
    const className = computed(() => {
      if (props.class) {
        return `svg-icon ${props.class}`;
      } else {
        return "svg-icon";
      }
    });
    const icon = computed(() => {
      return `#icon-${props.icon}`;
    });
    return () => (
      <svg class={className.value} aria-hidden="true">
        <use xlinkHref={icon.value} />
      </svg>
    );
  }
});

使用

import SvgIcon from "@/components/icon/SvgIcon";
import "@/assets/icons/alipay.svg";
import "@/assets/icons/qq.svg";
import "@/assets/icons/wechat.svg";

export default defineComponent({
    return () => (
      <div>
         <SvgIcon class="my-icon" icon="qq" />
         <SvgIcon class="my-icon" icon="wechat" />
         <SvgIcon class="my-icon" icon="alipay" />
      </div>
    );
  }
});

Logo

前往低代码交流专区

更多推荐