Last active
February 24, 2023 09:53
-
-
Save danielstgt/f60c25ea4e95d35af16d4cab9cbf4a0b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<svg v-bind="svgAttributes" v-html="svgContent"></svg> | |
</template> | |
<script> | |
export default { | |
props: ['icon'], | |
data() { | |
return { | |
svgContent: null, | |
svgAttributes: null, | |
} | |
}, | |
methods: { | |
loadSvg(url) { | |
var request = new XMLHttpRequest(); | |
request.onreadystatechange = () => { | |
if (request.readyState === XMLHttpRequest.DONE && request.status === 200) { | |
// set svgString | |
var svgString = request.responseText.trim(); | |
// set svgAttributes | |
var wrapper = document.createElement('div'); | |
wrapper.innerHTML = svgString; | |
var attributesList = wrapper.firstElementChild.attributes; | |
var attributes = {}; | |
Object.keys(attributesList).map(i => attributes[attributesList[i].name] = attributesList[i].value); | |
this.svgAttributes = attributes; | |
// set svgContent | |
this.svgContent = svgString.replace(/^<svg[^>]*>|<\/svg>$/g, ''); | |
} | |
}; | |
request.open('GET', url, true); | |
request.send(); | |
} | |
}, | |
mounted() { | |
this.loadSvg('/svg/' + this.icon.replace(new RegExp('.'.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1'), 'g'), '/') + '.svg'); | |
} | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment