vue中如何使用svg,以及碰到的相应问题

发布时间 2023-10-25 12:42:23作者: ajajaz

安装

cnpm install svg-sprite-loader --save-dev

创建svg文件夹存放svg图标

创建icons文件夹,在icons文件夹下创建svg文件夹存放本地svg图标。
image

vue.config.js 中配置svg图片

 config.module.rule("svg").exclude.add(resolve("src/icons")).end();
    config.module
      .rule("icons")
      .test(/\.svg$/)
      .include.add(resolve("src/icons"))
      .end()
      .use("svg-sprite-loader")
      .loader("svg-sprite-loader")
      .options({
        symbolId: "[name]", //注意这里,可能会导致svg不显示,要与vue文件中的name一致
      })
     .end();

创建SvgIcon公用组件

<template>
  <svg :class="getClassName" :width="width" :height="height" aria-hidden="true">
    <use :xlink:href="getName"></use>
  </svg>
</template>

<script>
export default {
  name: "icon-svg",
  props: {
    name: {
      type: String,
      required: true,
    },
    className: {
      type: String,
    },
    width: {
      type: String,
    },
    height: {
      type: String,
    },
  },
  computed: {
    getName() {
      return `#icon-${this.name}`;
    },
    getClassName() {
      if (this.className) {
        return "icon-svg svg-icon " + this.className;
      } else {
        return "icon-svg svg-icon";
      }
    },
  },
};
</script>

<style>
.icon-svg {
  width: 1em;
  height: 1em;
  fill: currentColor;
  overflow: hidden;
}
</style>

创建index.js 导入所有svg图标

icons文件夹创建index.js 自动导入所有svg图标。

/**
 * 字体图标, 统一使用SVG Sprite矢量图标(http://www.iconfont.cn/)
 *
 * 使用:
 *  1. 在阿里矢量图标站创建一个项目, 并添加图标(这一步非必须, 创建方便项目图标管理)
 *  2-1. 添加icon, 选中新增的icon图标, 复制代码 -> 下载 -> SVG下载 -> 粘贴代码(重命名)
 *  2-2. 添加icons, 下载图标库对应[iconfont.js]文件, 替换项目[./iconfont.js]文件
 *  3. 组件模版中使用 [<icon-svg name="canyin"></icon-svg>]
 *
 * 注意:
 *  1. 通过2-2 添加icons, getNameList方法无法返回对应数据
 */
import Vue from "vue";
import IconSvg from "@/components/icon-svg";

Vue.component("IconSvg", IconSvg);
// register globally

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

执行 requireContext.keys().map(requireContext)得到返回的数据:
image

main.js中引入icons/index.js

image

使用

image

问题解决

https://blog.csdn.net/qq_35119405/article/details/106115244