Skip to content

Instantly share code, notes, and snippets.

@ollejah
Last active July 7, 2017 16:45
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 ollejah/647207b37b1c533613542a5811f47eb5 to your computer and use it in GitHub Desktop.
Save ollejah/647207b37b1c533613542a5811f47eb5 to your computer and use it in GitHub Desktop.
Vue svg directive. Call #{sprite-id}
export default {
install(Vue, opts) {
Vue.directive('svg', {
bind(el, { value }) {
if (!value) {
return;
}
if (!opts.prefix) {
opts.prefix = '';
}
let svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
let use = document.createElementNS('http://www.w3.org/2000/svg', 'use');
let sprite = `${opts.prefix}${value}`;
// let scope = null;
// for (let key in el.attributes) {
// let attr = el.attributes[key].name;
// if (typeof attr === 'string' && attr.substr(0, 2) === '_v') {
// console.log(attr)
// scope = attr;
// }
// }
use.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', `${opts.sprites}#${sprite}`);
// use.setAttributeNS(null, scope, '');
if (el.tagName !== 'svg') {
// svg.setAttributeNS(null, scope, '');
if (opts.class) svg.classList.add(opts.class, sprite);
el.appendChild(svg);
el = svg;
}
if (opts.class) el.classList.add(opts.class, sprite);
el.appendChild(use);
}
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment