vue3使用vite-plugin-svg-icons加载SVG图片

本文介绍了如何在Vite项目中使用vite-plugin-svg-icons插件来管理SVG图标,包括配置、全局引入SVG组件、添加TypeScript支持以及实际使用的步骤。
摘要由CSDN通过智能技术生成

官方参考

1-安装

npm i vite-plugin-svg-icons -D

2-配置

vite.config.js中编辑

import { fileURLToPath, URL } from 'node:url'
import {createSvgIconsPlugin} from 'vite-plugin-svg-icons';

// 在plugins增加 createSvgIconsPlugin插件
export default defineConfig({
  plugins: [
    createSvgIconsPlugin({
      iconDirs: [fileURLToPath(new URL('./src/assets/svgs', import.meta.url))],
      symbolId: 'icon-[dir]-[name]',
    })
  ]
})

3-引入

在src/main.ts进行全局引入

import 'virtual:svg-icons-register'

4-具体实现:

增加SVG组件

src/components目录下新增文件夹SvgIcon,并在该目录下新增文件index.vue,代码如下:

<!-- SVG图标 -->
<script setup lang="ts">
import {computed} from 'vue';
import {useSystemStore} from '@/store/system';

const props = defineProps({
  prefix: {
    type: String,
    default: 'icon'
  },
  name: {
    type: String,
    required: true
  },
 color: {
    type: String,
    required: true,
    default:'#fc4a14'
  }
});
const symbolId = computed(() => `#${props.prefix}-${props.name}`);
</script>
<template>
  <!-- 有时修改颜色不成功得到的经验:修改svg颜色,需要去内部svg文件中比如login_username.svg中删除掉fill样式才生效 目前这些svg都是定义在class 比如.cls-2{fill:**}把样式删除即可  -->
  <svg aria-hidden="true">
    <use :xlink:href="symbolId" :fill="color" />
  </svg>
</template>

全局组件挂载 (main.ts)

import SvgIcon from '@/components/SvgIcon/index.vue';
app.component('SvgIcon', SvgIcon);

添加Typescript支持

在tsconfig.app.json进行设置

{
  "compilerOptions": {
    "types": ["vite-plugin-svg-icons/client"]
  }
}

具体使用

1-从UI那里拿到svg文件存放在src/assets/svgs下,并命名,比如命名为username.svg
2-具体使用参考:

<template>
  <div class="w-full h-full flex flex-col justify-start items-start">
    <!--  name参数这里填写图标文件名不需要加上svg  -->
    <SvgIcon name="username" class="w-[24px] h-[24px] object-scale-down text-amber-500"/>
  </div>
</template>


 

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值