Table of Contents
URL: https://www.progressiverobot.com/vuejs-using-svg-icons/
While font-based icons ruled the world a year or two ago, embedded SVG icons have since taken the stage (often credited to this post) as the best way to include icons in your app. Unfortunately, adding them by hand requires a lot of work and duplicated effort. Thankfully, vue-svgicon aims to simplify this and does a wonderful job.
Let's get started with it shall we?
Installation & Setup
<^>vue-svgicon<^> can be installed via Yarn or NPM as expected:
# Yarn
$ yarn add vue-svgicon -D
# NPM
$ npm install vue-svgicon --save-dev
Next, download your preferred Icon font with individual SVG icons per-glyph. I'll be using the Material Design Icons set, one of the largest sets available with almost 2,000 individual glyphs, based on Google's design guidelines but sourced mostly from the community.
Stick those <^>.svg<^> files in an <^>svg-icons<^> folder at the root of your project. (Outside of the <^>src<^> directory.)
Now, <^>vue-svgicon<^> needs to convert all of the svg icon files into <^>.js<^> files that can be individually loaded, so let's add a quick <^>NPM script<^> to do this for us. Edit your <^>package.json<^> file to include the script below:
[label package.json]
{
...
"scripts": {
...
"generate-icons": "vsvg -s ./svg-icons -t ./src/compiled-icons"
}
...
}
Then issue the command <^>npm run generate-icons<^>. This will output the compiled icons at src/compiled-icons/[icon-name].js.
Usage
Now we need to load the icons in our app. Add the <^>vue-svgicon<^> plugin to your main Vue app file:
[label src/main.js]
...
import VueSVGIcon from 'vue-svgicon'
Vue.use(VueSVGIcon)
...
Now, we can load icons in our components by using the <svgicon> element and importing the icon we're using. As a wonderful bonus, by using <^>SVG icons<^> in this way, we can load only the icons we need in the app with almost no effort.
[label src/ExampleComponent.vue]
<template>
<div>
<span>Icon Demonstration:</span>
<!-- You can tweak the width, height, and color of the icon. -->
<svgicon icon="menu" width="22" height="18" color="#0f2"></svgicon>
</div>
</template>
<script>
// If you really, really need to, you can import the whole iconset in your main.js file with `import ./compiled-icons`.
import './compiled-icons/menu';
</script>
There are a few other neat little tricks <^>vue-svgicon<^> has up its sleeve, find out more at the official repository.