1. 安装vite-plugin-svg-icons插件
npm i vite-plugin-svg-icons -D
2.vite.config.ts中配置
import path from "path"; import { createSvgIconsPlugin } from "vite-plugin-svg-icons"; export default defineConfig({ plugins: [ ...... createSvgIconsPlugin({ iconDirs: [path.resolve(process.cwd(), "src/assets/svgs")], // 指定symbolId格式 symbolId: "[name]", customDomId: "turing-planet-svgs", // 避免多项目互相影响 }) ], ...... })
3.main.ts引入
//svg插件需要配置代码 import 'virtual:svg-icons-register';
4.在src/assets中新建目录svgs, 将所有的的svg图片放在svgs文件中
5.封装svg-icon.vue组件
<template> <svg :class="className" :style="{ width, height: _height }"> <use :xlink:href="iconName"></use> </svg> </template> <script setup lang="ts"> import { computed } from "vue"; const props = defineProps({ name: { type: String, require: true }, width: { type: String, default: "16px" }, height: { type: String }, className: { type: String }, }); const _height = computed(() => { return props.height ? props.height : props.width; }); const iconName = computed(() => { return `#${props.name}`; }); </script> <style lang="scss" scoped></style>
6.全局注册svg-icon组件
7.vue文件中使用
<svg-icon name="file-icon" width="28px" height="20px"/>
标签:String,自定义,icons,svg,Vue3,height,props,vite From: https://www.cnblogs.com/liuminxiu0707/p/18143399