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

记录一下,方便后续查阅

相关推荐
咖啡续命又一天20 分钟前
python 自动化采集 ChromeDriver 安装
开发语言·python·自动化
FuckPatience34 分钟前
Vue ASP.Net Core WebApi 前后端传参
前端·javascript·vue.js
huohaiyu1 小时前
synchronized (Java)
java·开发语言·安全·synchronized
一枚前端小能手1 小时前
🔥 SSR服务端渲染实战技巧 - 从零到一构建高性能全栈应用
前端·javascript
Komorebi_99991 小时前
Vue3 provide/inject 详细组件关系说明
前端·javascript·vue.js
_OP_CHEN1 小时前
C++基础:(九)string类的使用与模拟实现
开发语言·c++·stl·string·string类·c++容器·stl模拟实现
蓝天智能1 小时前
QT MVC中View的特点及使用注意事项
开发语言·qt·mvc
不一样的少年_1 小时前
【前端效率工具】:告别右键另存,不到 50 行代码一键批量下载网页图片
前端·javascript·浏览器
Asort1 小时前
JavaScript设计模式(八):组合模式(Composite)——构建灵活可扩展的树形对象结构
前端·javascript·设计模式
木觞清2 小时前
喜马拉雅音频链接逆向实战
开发语言·前端·javascript