Vue3 vite SVG图标使用

一、SVG图标配置

1、安装依赖

npm install vite-plugin-svg-icons

2、在vite.config.ts中配置插件

import { fileURLToPath, URL } from 'node:url'
import VueSetupExtend from 'vite-plugin-vue-setup-extend'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'
// import vueDevTools from 'vite-plugin-vue-devtools'

// https://vite.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    // vueDevTools(),
    // 组件命名
    VueSetupExtend(),
    // SVG插件
    createSvgIconsPlugin({
      iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
      symbolId: 'icon-[dir]-[name]',
      svgoOptions: {
        // 添加 SVGO 配置
        plugins: [
          {
            name: 'removeAttrs',
            params: { attrs: 'stroke' },  //不删除背景色 fill属性
       //params: { attrs:
'fill' }, // 删除 fill 属性
        
}, ], }, }), ], resolve: { alias: { '@': fileURLToPath(new URL('./src', import.meta.url)), }, }, })

3、main.ts 导入

import 'virtual:svg-icons-register'

注意:已经设置自动清除SVG的fill,若不清除,则fill无效

二、获取SVG图标

1、阿里图标库

https://www.iconfont.cn/

2、选中图标,点击下载,复制SVG代码

 3、新建 icons 文件夹

位置:src/assets/icons,与上面的配置文件对于

4、新建文件

xx.svg,并把复制的SVG代码,粘贴

三、封装

1、新建 

文件: SvgIcon.vue 

路径:src/components

2、内容

<template>
    <svg :style="{width:width,height:height}"  >
        <use :xlink:href="prefix + name" :fill="color"></use>
    </svg>
</template>
<script setup lang="ts" name="SvgIcon">
  // SVG图标的 名字、颜色、高度、宽度
  defineProps({
    width:{
      type:[String, Number],
      default: 20
    },
    height:{
      type:[String, Number],
      default: 20
    },
    color:{
      type:String,
      default: "#2c2c2c"
    },
    prefix:{
      type:String,
      default:"#icon-"
    },
    name:String,

  }
)
</script>

四、注册全局组件

main.ts

1、引入

import SvgIcon from './components/SvgIcon.vue'

2、注册

app.component('SvgIcon', SvgIcon)

五、使用

 

<svg-icon name="love" width="40" height="40" color="red"></svg-icon>

 

posted @ 2025-03-22 10:54  市丸银  阅读(271)  评论(0)    收藏  举报