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?
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:
{
...
"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
.
Now we need to load the icons in our app. Add the vue-svgicon plugin to your main Vue app file:
...
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.
<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.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!