Skip to content

Instantly share code, notes, and snippets.

@danielstgt
Last active February 24, 2023 09:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielstgt/f60c25ea4e95d35af16d4cab9cbf4a0b to your computer and use it in GitHub Desktop.
Save danielstgt/f60c25ea4e95d35af16d4cab9cbf4a0b to your computer and use it in GitHub Desktop.
<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