-
Notifications
You must be signed in to change notification settings - Fork 1
/
svg-vue.vue
40 lines (31 loc) · 1.1 KB
/
svg-vue.vue
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<template>
<svg
v-bind="svgAttributes"
v-html="svgContent"
>
</svg>
</template>
<script>
import { computed } from 'vue';
export default {
name: 'SvgVue',
props: {
icon: String
},
setup(props) {
const iconPath = computed(() => props.icon.replace(new RegExp('.'.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1'), 'g'), '/') + '.svg');
const svgString = computed(() => require(`svg-files-path/${iconPath.value}`).default);
const svgAttributes = computed(() => {
if (! svgString) return {};
let wrapper = document.createElement('div');
wrapper.innerHTML = svgString.value;
let attributesList = wrapper.firstElementChild.attributes;
let attributes = {};
Object.keys(attributesList).map(i => attributes[attributesList[i].name] = attributesList[i].value);
return attributes;
});
const svgContent = computed(() => svgString ? svgString.value.replace(/^<svg[^>]*>|<\/svg>$/g, '') : null);
return { svgAttributes, svgContent };
}
}
</script>