在开发低代码平台,写数字矩形图组件时,提供配置不同的前缀图标,平台提供了多种SVG供用户选择,也可以由用户上传,针对与平台提供的SVG需要修改颜色大小。
1.安装vite-plugin-svg-icons
npm i vite-plugin-svg-icons -D
2.vite.config.ts中配置插件
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'
export default () => {
return {
plugins: [
createSvgIconsPlugin({
<!-- svg所在文件夹位置 -->
iconDirs: [path.resolve(process.cwd(), 'src/assets/icon/svg')],
symbolId: 'icon-[dir]-[name]',
}),
],
}
}
3.创建SVG组件
<template>
<svg aria-hidden="true" class="svg-icon" :width="props.size" :height="props.size">
<defs>
<linearGradient id="gradient" v-bind="direction">
<stop offset="0%" :stop-color="props.color" />
<stop offset="100%" :stop-color="props.gradientColor" />
</linearGradient>
</defs>
<use :xlink:href="symbolId" :fill="svgFill" />
</svg>
</template>
<script setup>
import { computed } from 'vue';
const props = defineProps({
prefix: {
type: String,
default: 'icon'
},
name: {
type: String,
required: true
},
color: {
type: String,
default: '#333'
},
size: {
type: String,
default: '1em'
},
gradientColor: {
type: String,
default: ''
},
gradientAngle: {
type: String,
default: '1'
}
});
const symbolId = computed(() => `#${props.prefix}-${props.name}`);
const svgFill = computed(() => {
if (props.gradientColor) {
return 'url(#gradient)';
}
return props.color;
});
const direction = computed(() => {
switch (props.gradientAngle) {
case '1':
return { x1: '0%', x2: '100%', y1: '0%', y2: '0%' };
case '2':
return { x1: '0%', x2: '100%', y1: '100%', y2: '0%' };
case '3':
return { x1: '0%', x2: '0%', y1: '100%', y2: '0%' };
case '4':
return { x1: '100%', x2: '0%', y1: '100%', y2: '0%' };
case '5':
return { x1: '100%', x2: '0%', y1: '0%', y2: '0%' };
case '6':
return { x1: '0%', x2: '100%', y1: '0%', y2: '100%' };
case '7':
return { x1: '0%', x2: '0%', y1: '0%', y2: '100%' };
case '8':
return { x1: '100%', x2: '0%', y1: '0%', y2: '100%' };
default:
return { x1: '0%', x2: '100%', y1: '0%', y2: '0%' };
}
});
</script>
4.在src/main.js全局注册组件并内引入注册脚本
import { createApp } from 'vue'
import App from './App.vue'
import svgIcon from "@/components/SvgIcon/index.vue";
import 'virtual:svg-icons-register'
const app = createApp(App)
app.component('svg-icon', svgIcon).mount('#app')
5.使用
<svg-icon v-bind=“svgConfig” />