Home

Awesome

vue-svg-sprite

stable NPM version Coverage Status Commitizen friendly Conventional Commits License

Vue.js component or directive to simply use SVG sprites

🚨 This new version (2.x) is for Vue.js 3. For v2 compatibility, check previous version

Description

This Vue.js plugin will help you to manage SVG spritsheet with <symbol> elements. It provides a component / directive to make tu use of <svg> and <use> elements easier.

This module is tree-shakable and exports the followings:

820B gzipped for the component plugin…

It's also TypeScript friendly :)

Overall usage

NB: If the className is already used (eg: via a modifier like icon--inline), the class option is not added…


Setup

Component (plugin + local)

// File: main.ts
// Global registration with options
import Vue from 'vue'
import { svgSpritePlugin } from 'vue-svg-sprite'

Vue.use(svgSpritePlugin, {} /* options */)
<script>
  // File: Parent.vue
  // Local use
  import { SvgSprite } from 'vue-svg-sprite'

  export default {
    components: {
      SvgSprite,
    },
  }
</script>

Directive (plugin)

// File: main.ts
// Global registration with options
import Vue from 'vue'
import { svgSpriteDirectivePlugin } from 'vue-svg-sprite'

Vue.use(svgSpriteDirectivePlugin, {} /* options */)

Options

OptionDefaultDescription
url'/assets/svg/sprite.svg'path to external SVG file
class'icon'CSS class name
Vue.use(svgSpritePlugin, {
  url: 'path/to/svg/file.svg',
  class: 'my-class',
})

If you want to use an inline SVG, set url to ''.<br> If your spritesheet is "processed" (vue-cli, webpack, …) set url to require('./processed/path/to/svg/sprite.svg').


Usage

Component

<SvgSprite symbol="icons-dashboard" size="24" />

Directive

<svg v-svg symbol="icons-dashboard" size="24"></svg>

You can also use an expression (<svg v-svg="'icons-dashboard'"></svg>).

Attributes (all)

AttributeRequiredDefaultDescription
symbol*-symbol id
size-generate viewBox, width and height
urloptions.urlhref domain or '' for inline SVG

size attributes gives the same output with 24, 24 24 or 0 0 24 24.

Example

<SvgSprite
  symbol="icons-dashboard"
  size="0 0 24 24"
  role="presentation"
  class="icon--inline"
/>

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"
    href="/assets/svg/sprite.svg#icons-dashboard"
  ></use>
</svg>

To generate the SVG sprite file, you can use svg-sprite.


Contributors

@lovethebomb @eregnier @jpsc @valjar @demiro @Warin @Warcot @zavsievich

License

See UNLICENSE for details.