Created
March 19, 2018 22:36
-
-
Save davestewart/54b6823a76500fdcdd918fc5ce575d4c to your computer and use it in GitHub Desktop.
Vue provide inject example for customisable icons
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> | |
<ui-icon name="notes" /> | |
<ui-icon name="book" /> | |
<ui-icon name="map" /> | |
</template> |
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
// add icons to the list as you need them... | |
export default { | |
notes: require('./notes.svg'), | |
book: require('./book.svg'), | |
map: require('./map.svg'), | |
} |
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
// App | |
import App from 'App.vue' | |
// fixed icon component | |
import UiIcon from 'UiIcon.vue' | |
Vue.component('ui-icon', UiIcon) | |
// flexible icon assets | |
import icons from 'icons.js' | |
// run all | |
const app = new Vue({ | |
el: '#app', | |
template: '<App/>', | |
components: { App }, | |
provide: { | |
icons | |
} | |
}) | |
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> | |
<i class="icon svg-icon" v-html="svg"></i> | |
</template> | |
<script> | |
export default { | |
inject: ['icons'], | |
props: { | |
'name': String | |
}, | |
computed: { | |
svg () { | |
if (!this.icons) { | |
throw new Error(message) | |
} | |
const svg = this.icons[this.name] | |
if (!svg) { | |
throw new Error(`Unknown icon "${this.name}"`) | |
} | |
return svg | |
.replace(/<\?xml.+?>/, '') | |
.replace(/<!--.+?-->/, '') | |
} | |
}, | |
} | |
const message = `Warning: icons definitions have not been provided! | |
Add... | |
provide: { | |
icons: { | |
foo: '<svg> ... </svg>', | |
... | |
} | |
} | |
...to your app's declaration to inject SVG icon definitions. | |
See https://vuejs.org/v2/api/#provide-inject for more info` | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment