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

记录一下,方便后续查阅

相关推荐
paterWang1 小时前
基于 Python 和 OpenCV 的酒店客房入侵检测系统设计与实现
开发语言·python·opencv
东方佑1 小时前
使用Python和OpenCV实现图像像素压缩与解压
开发语言·python·opencv
天宇&嘘月2 小时前
web第三次作业
前端·javascript·css
我真不会起名字啊2 小时前
“深入浅出”系列之杂谈篇:(3)Qt5和Qt6该学哪个?
开发语言·qt
laimaxgg2 小时前
Qt常用控件之单选按钮QRadioButton
开发语言·c++·qt·ui·qt5
水瓶丫头站住2 小时前
Qt的QStackedWidget样式设置
开发语言·qt
小王不会写code2 小时前
axios
前端·javascript·axios
小钊(求职中)3 小时前
Java开发实习面试笔试题(含答案)
java·开发语言·spring boot·spring·面试·tomcat·maven
luckyext4 小时前
HBuilderX中,VUE生成随机数字,vue调用随机数函数
前端·javascript·vue.js·微信小程序·小程序
小小码农(找工作版)4 小时前
JavaScript 前端面试 4(作用域链、this)
前端·javascript·面试