vue3.0+ts+element ui中如何使用svg图片

1、安装一下依赖

javascript 复制代码
npm install vite-plugin-svg-icons -D

2、在vite.config.ts中

javascript 复制代码
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons';
const { resolve } = require('path');
plugins:[
    createSvgIconsPlugin({
      // 配置你存放 svg 图标的目录
      iconDirs: [resolve(process.cwd(), 'svg文件夹所在的目录')],//例如:src/images/svg
      // 定义 symbolId 格式
      symbolId: 'icon-[dir]-[name]',
    })
]

3、封装一个svg组件

javascript 复制代码
<template>
  <svg :class="svgClass" aria-hidden="true">
    <use :xlink:href="iconName" :fill="color"></use>
  </svg>
</template>

<script>
import { computed, defineComponent } from 'vue';
export default defineComponent({
  props: {
    iconClass: {
      type: String,
      required: true,
    },
    className: {
      type: String,
      default: '',
    },
    color: {
      type: String,
      default: '#889aa4',
    },
  },
  setup(props) {
    return {
      iconName: computed(() => `#icon-${props.iconClass}`),
      svgClass: computed(() => {
        if (props.className) {
          return `svg-icon ${props.className}`;
        }
        return 'svg-icon';
      }),
    };
  },
});
</script>

<style scope>
.svg-icon {
  width: 1em;
  height: 1em;
  fill: currentColor;
  vertical-align: middle;
}
</style>

4、继续引入

javascript 复制代码
//在main.ts中
import 'virtual:svg-icons-register';
//在main.ts中全局引入
import svgIcon from '组件地址';
app.component('svgIcon', svgIcon);

记录一下,方便后续查阅

相关推荐
源代码•宸3 小时前
分布式缓存-GO(分布式算法之一致性哈希、缓存对外服务化)
开发语言·经验分享·分布式·后端·算法·缓存·golang
云和数据.ChenGuang3 小时前
PHP-FPM返回的File not found.”的本质
开发语言·php·运维工程师·运维技术
R.lin3 小时前
Java 8日期时间API完全指南
java·开发语言·python
哆啦A梦15883 小时前
商城后台管理系统 03 登录布局
javascript·vue.js·elementui
yangpipi-3 小时前
《C++并发编程实战》 第4章 并发操作的同步
开发语言·c++
火钳游侠4 小时前
java单行注释,多行注释,文档注释
java·开发语言
曼巴UE54 小时前
UE FString, FName ,FText 三者转换,再次学习,官方文档理解
服务器·前端·javascript
有趣的我4 小时前
C++ 多态介绍
开发语言·c++
selt7914 小时前
Redisson之RedissonLock源码完全解析
android·java·javascript
fie88894 小时前
波束赋形MATLAB代码实现
开发语言·matlab