Skip to content

Instantly share code, notes, and snippets.

@davestewart
Created March 19, 2018 22:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save davestewart/54b6823a76500fdcdd918fc5ce575d4c to your computer and use it in GitHub Desktop.
Save davestewart/54b6823a76500fdcdd918fc5ce575d4c to your computer and use it in GitHub Desktop.
Vue provide inject example for customisable icons
<template>
<ui-icon name="notes" />
<ui-icon name="book" />
<ui-icon name="map" />
</template>
// add icons to the list as you need them...
export default {
notes: require('./notes.svg'),
book: require('./book.svg'),
map: require('./map.svg'),
}
// 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
}
})
<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