1.将svg图片放入项目的src\assets\icons路径,如下图
2.封装一个组件名为SvgIcon的组件,封装如下:
<template>
<svg aria-hidden="true" class="svg-icon">
<use :xlink:href="symbolId" :fill="color" />
</svg>
</template>
<script setup lang="ts">
import { computed } from 'vue';
const props = defineProps({
prefix: {
type: String,
default: 'icon'
},
iconClass: {
type: String,
required: false
},
color: {
type: String,
default: ''
}
});
const symbolId = computed(() => `#${props.prefix}-${props.iconClass}`);
</script>
<style scoped>
.svg-icon {
width: 1em;
height: 1em;
vertical-align: -0.15em;
overflow: hidden;
fill: currentColor;
}
</style>
3.在需要使用的地方,如下两步即可显示svg图片
//引入组件
import SvgIcon from '@/components/SvgIcon/index.vue';
//使用组件
<svg-icon
:icon-class="islineChart?'line-chart':'build'"
@click="islineChart = !islineChart"
color="#409eff"
style="width: 30px;height: 30px;"
/>
4.显示效果如下
:icon-class为'line-chart'时
:icon-class为'build'时