Vue.js directive to simply use SVG sprite
This version (1.x.x) is compatible with Vue.js 2.0 (thanks to @lovethebomb)
This Vue.js plugin will add some attributes (viewBox
, width
and height
) and the appropriate <use>
to <svg>
elements.
- Use inline SVG spritesheet or an external SVG file
- Use
expression
orsymbol
attribute to link the correct<symbol>
- Use
size
attribute forviewBox
,width
andheight
(<svg>
)- Comma or space separated values
- 1, 2 or 4 values accepted
- 1 value: x/y = 0, width = height (e.g.: 24)
- 2 values: x/y = 0, width, height (e.g.: 24 24)
- 4 values: x, y, width, height (e.g.: 0 0 24 24)
- Options:
url
: path to external SVG file (default:/assets/svg/sprite.svg
, use''
for inline)class
: class for the SVG element (default:icon
)
NB: If the className is already used (eg: via a modifier like icon--inline
), the class option is not added…
import Vue from 'vue';
import SvgSprite from 'vue-svg-sprite';
Vue.use(SvgSprite);
If you are using this plugin with vue-server-renderer (directly or under the hood: NuxtJS, Vapper, …), server needs to render the directive specifically:
// Some config file…
const SvgSprite = require('vue-svg-sprite')
module.exports = {
rendererOptions: {
directives: {
svg(vnode, directiveMeta) {
SvgSprite.ssr(vnode, directiveMeta)
},
},
},
}
If you are using this plugin with Nuxt make sure you import as a plugin without SSR since document.createElementNS
does not exist.
plugins: [
{ src: '~/plugins/svg-sprite.js', ssr: false }
]
<svg v-svg
symbol="icons-dashboard"
size="0 0 24 24"
role="presentation"
class="icon--inline"
></svg>
you can use an expression rather than the
symbol
(<svg v-svg="'icons-dashboard'"></svg>
).size
attributes gives the same output with"24"
,"24 24"
or"0 0 24 24"
.
output:
<svg viewBox="0 0 24 24" width="24" height="24" role="presentation" class="icon--inline">
<use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="/assets/svg/sprite.svg#icons-dashboard"></use>
</svg>
Option | Values | Default | Description |
---|---|---|---|
url | String | '/assets/svg/sprite.svg' | path to external SVG file |
class | String | 'icon' | CSS class name |
Vue.use(SvgSprite, {
url: 'path/to/svg/file.svg',
class: 'my-class',
});
If you want to use an inline SVG, set
url
option to''
.
To generate the SVG sprite file, you can use gulp-svgstore or grunt-svgstore.
@lovethebomb @eregnier @jpsc @valjar @demiro @Warin
MIT, see LICENSE.md for details.