Vue3加載遠(yuǎn)程服務(wù)器的svg圖標(biāo)文件,并實(shí)現(xiàn)顏色、大小的可控
準(zhǔn)備svg文件
<svg width="inherit" height="inherit" viewBox="0 0 20 20" fill="currentColor" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<rect id="ic-用戶" width="20.000000" height="20.000000" fill="inherit" fill-opacity="0"/>
<path id="矢量 77" d="M6 6C6 3.79 7.8 2 10 2C12.2 2 14 3.79 14 6C14 8.2 12.2 10 10 10C7.8 10 6 8.2 6 6ZM12.5 6C12.5 4.59 11.4 3.5 10 3.5C8.59 3.5 7.5 4.59 7.5 6C7.5 7.4 8.59 8.5 10 8.5C11.4 8.5 12.5 7.4 12.5 6ZM3.5 12.7C5.59 11.6 7.8 11.1 10 11.1C12.2 11.1 14.4 11.7 16.5 12.7C16.79 12.9 17 13.2 17 13.6L17 17C17 17.6 16.6 18 16 18L4 18C3.4 18 3 17.6 3 17L3 13.6C3 13.2 3.19 12.9 3.5 12.7ZM15.5 13.9C13.8 13 11.9 12.6 10 12.6C8.09 12.6 6.19 13.1 4.5 13.9L4.5 16.5L15.5 16.5L15.5 13.9Z" fill="inherit" fill-opacity="1.000000" fill-rule="evenodd"/>
</svg>
注意點(diǎn)
- width藕咏、height 值要設(shè)置為 inherit
- fill 值設(shè)置為 currentColor
- 內(nèi)部元素標(biāo)簽的 fill 值設(shè)置為 inherit
封裝iconSvg.vue組件
<template>
<div
:style="{
color: color,
width: width,
height: height,
transform: transform,
}"
v-html="svgContent"
></div>
</template>
<script setup >
import { onMounted, ref, computed, onBeforeUnmount } from "vue";
import axios from "axios";
const props = defineProps({
type: {
type: String,
default: "",
},
color: {
type: String,
default: "#00ff00",
},
width: {
type: String,
default: "20px",
},
height: {
type: Number,
default: "20px",
},
rotate: {
type: Number,
default: 0,
},
scale: {
type: Number,
default: 1,
},
});
const svgContent = ref("");
const transform = computed(() => {
return "rotate(" + props.rotate + "deg) scale(" + props.scale + ")";
});
onMounted(() => {
axios.get(props.type).then((res) => {
svgContent.value = res.data;
});
});
</script>
<style scoped lang="less">
</style>
測(cè)試 test.vue
<template>
<div style="position: relative; top: 50%; left: 50%">
<iconSvg
:type="svgInfo.type"
:color="svgInfo.color"
:width="svgInfo.width"
:height="svgInfo.height"
:rotate="svgInfo.rotate"
:scale="svgInfo.scale"
></iconSvg>
</div>
</template>
<script setup >
import { onMounted, reactive, ref } from "vue";
import iconSvg from "./iconSvg/index.vue";
const svgInfo = reactive({
type: "sidebar-user.svg",
color: "#000000",
width: "20px",
height: "20px",
rotate: 0,
scale: 1,
});
setInterval(() => {
let r = 255 * Math.random();
let g = 255 * Math.random();
let b = 255 * Math.random();
svgInfo.color = `rgb(${r},${g},$弱匪)`;
svgInfo.width = "20px";
svgInfo.height = "20px";
svgInfo.rotate += 1;
svgInfo.scale += 0.02;
}, 100);
</script>
<style scoped lang="less">
</style>