封装Svg

发布时间 2023-09-20 15:57:21作者: Baipei
1、npm i vite-plugin-svg-icons  
npm i fast-glob
 
 
2、在assets下创建svg目录    找想要的图标复制svg代码放到svg
在vite.config.js配置:
import {createSvgIconsPlugin}from 'vite-plugin-svg-icons'

// 在plugins中添加
createSvgIconsPlugin({
iconDirs: [resolve(process.cwd(), 'src/assets/svg')],
symbolId: 'icon-[dir]-[name]',
}),

3、在man.js导入

// 导入svg图标
import 'virtual:svg-icons-register'

4、

<template>
<svg aria-hidden="true" :style="{ width: size + 'px', height: size + 'px' }">
<use :xlink:href="symbolId" :fill="color" />
</svg>
</template>
<script setup lang="ts">
import { computed } from 'vue';

const props = defineProps({
iconName: {
type: String,
required: true
},
color: {
type: String,
default: ''
},
size: {
type: [Number, String],
default: 18
}
})
const symbolId = computed(() => `#icon-${props.iconName}`);

</script>


<style scoped>
.svg-icon {
fill: currentColor;
vertical-align: middle;
}
</style>

5、导入组件并使用

import SvgIcon from '@/components/SvgIcon.vue'
<SvgIcon icon-name="location" class="bread-crumb-icon"></SvgIcon>