Managing a custom collection of icons in a Vue app can be challenging at times. An icon font is easy to use, but for customization, you have to rely on third-party font generators, and merge conflicts can be painful to resolve since fonts are binary files.
Using SVG files instead can eliminate those pain points, but how can we ensure they’re just as easy to use while also making it easy to add or remove icons?
Here is what my ideal icon system looks like:
To add icons, you just drop them into a designated icons folder. If you no longer need an icon, you simply delete it.To use the rocket.svg icon in a template, the syntax is as simple as
This component is much simpler. As previously mentioned, we leverage the
That’s it! If you want to use the icon component anywhere in your app without having to import it into every component that needs it, be sure to register the component in your main.js file:
import Vue from vue
import SvgIcon from @/components/SvgIcon.vue
Here are a few ideas for improvements, which I intentionally left out to keep this solution approachable:
Scale icons that have non-square dimensions to maintain their proportionsInject the SVG sprite into the page without needing an additional component.Make it work with vite, which is a new, fast (and webpack-free) build tool from Vue creator Evan You.Leverage the Vue 3 Composition API.
If you want to quickly take these components for a spin, I’ve created a demo app based on the default vue-cli template. I hope this helps you develop an implementation that fits your app’s needs!
¹ If you’re wondering why we’re using SVG when we want it to behave like an icon font, then check out the classic post that pits the two against one another.