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);

记录一下,方便后续查阅

相关推荐
ZC跨境爬虫3 分钟前
跟着 MDN 学 HTML day_29:(动态构建与更新 DOM 树)
前端·javascript·ui·html·html5·媒体
qq_375916374 分钟前
kettle菜鸟教程
开发语言·kettle
qq_2546744111 分钟前
Alpine Linux 基于 Debian 等系统的常规 Nginx
开发语言
故事和你9116 分钟前
洛谷-数据结构2-1-二叉堆与树状数组1
开发语言·数据结构·c++·算法·动态规划·图论
挨踢ren17 分钟前
C++虚函数:从基础到高阶
java·开发语言·jvm
hhb_61824 分钟前
C语言核心技术难点梳理与实战案例解析
c语言·开发语言
海参崴-28 分钟前
C++ STL篇 红黑树的模拟实现
开发语言·c++
Dshuishui34 分钟前
我用 Claude Code 做了一个学术论文搜索工具
开发语言·人工智能·python·pip·uv
Resky081835 分钟前
ReentrantReadWriteLock 深度解析
java·开发语言·juc
搜狐技术产品小编20231 小时前
深度解析与业务实战:将 screenshot-to-code 改造为支持 React + Ant Design 的前端利器
前端·javascript·react.js·前端框架·ecmascript