Create a base component and register it globally since you'll use it very frequently.
Create a <BaseIcon>
component that uses require
with expression to create a context for the SVG modules:
<template>
<Component
:is="require(`@/assets/svgs/${name}.svg`).default"
class="BaseIcon"
v-bind="$attrs"
@v-on="$listeners"
/>
</template>
<script>
export default {
name: 'BaseIcon',
// Transparent wrapper component
// https://v2.vuejs.org/v2/guide/components-props.html#Disabling-Attribute-Inheritance
inheritAttrs: false,
props: {
name: {
type: String,
required: true,
},
},
}
</script>
<style>
.BaseIcon {
/* Add some default CSS declaration blocks */
}
</style>
Note: We use <Component>
to handle dynamic components, which assumes you'll use vue-svg-loader
and the SVGs are treated as components. If that is not the case, use an <img>
tag instead and use src
instead of is
.
Registering the base component globally:
If you're only creating a single base component, you can just go to your main.js
file and before mounting the app do:
import Vue from 'vue'
import BaseIcon from './components/_base/BaseIcon.vue'
import App from './App.vue'
Vue.component('BaseIcon', BaseIcon)
Vue.config.productionTip = false
new Vue({
render: h => h(App),
}).$mount('#app')
Else, if you want something a little bit more complex, take a look at how this boilerplate registers base components automatically.
Finally, use the component like so:
<template>
<div>
<BaseIcon
name="info"
/>
<BaseIcon
name="help"
/>
<BaseIcon
name="close"
/>
</div>
</template>
<script>
export default {
name: 'SomeComp',
}
</script>