Vue3 + Vite + Ts 使用svg图片

  • 预加载 在项目运行时就生成所有图标
  • 高性能 内置缓存,仅当文件被修改时才会重新生成

安装依赖

// yarn 安装
yarn add vite-plugin-svg-icons
// npm 安装
npm i vite-plugin-svg-icons

配置

在 vite.config.ts 中配置插件

import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
export default defineConfig({
  plugins: [
    vue(),
    createSvgIconsPlugin({
      // src/assets/img/sv 是存放 svg 图片的目录
      iconDirs: [path.resolve(process.cwd(), "src/assets/img/svg")],
      symbolId: "icon-[name]",
    }),
  ],
});

注册

在 main.ts 中注册

import "virtual:svg-icons-register";

使用及封装

1,封装
在 components 文件夹中创建 svgIcon.vue 文件

<script>
import { defineComponent, computed } from "vue";
export default defineComponent({
  /**
  * name svg 图片名称
  * color 图片颜色
  * className 自定义样式
  */
  props: {
    name: {
      type: String,
      required: true,
    },
    color: {
      type: String,
      default: "",
    },
    className: {
      type: String,
      default: "",
    },
  },
  setup(props) {
    return {
      svgClass: computed(() => {
        if (props.className) {
          return `svg-icon ${props.className}`;
        }
        return "svg-icon";
      }),
    };
  },
});
</script>

<template>
  <svg aria-hidden="true" :class="svgClass">
    <use :href="`#icon-${name}`" :fill="color" />
  </svg>
</template>

<style lang="scss" scoped>
.sub-el-icon,
.nav-icon {
  display: inline-block;
  font-size: 15px;
  margin-right: 12px;
  position: relative;
}
.svg-icon {
  width: 1em;
  height: 1em;
  position: relative;
  fill: currentColor;
  vertical-align: -2px;
}
</style>

2,使用

import SvgIcon from "@/components/svgIcon.vue";
<SvgIcon :name="form" />

3,报错及修复
在这里插入图片描述
安装一下依赖就好了

npm i fast-glob

仓库地址

https://gitee.com/luliangweb/admin-template

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

卷不动了阿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值