A tiny Vue SVG icon component — an alternative to the icon-fonts

Andrejs Abrickis
2 min readMar 9, 2019

Nowadays it's hard to find a website or web application which doesn't use few or more SVG icons in its UI. A common approach is to use the <img> tag providing the source of the icon image or icon fonts.

Whenever using the <img> tag and there's a need to change the color of the icon we have to change the value of src attribute which results in a new request.

On the other hand, when icon fonts are used, all it takes is to change the CSS color property of an element. The cons are there's no way to change the color of one or more parts of the icon and we have to download the whole bundle of icons.

A solution for both cases is to use the <svg> tag and inline the icon's SVG markup into the HTML which results in many manually written <svg> tags all over the HTML. And additionally, in all of them, we have to manually add the attributes over again.

From my experience, a quick and simple solution is to create a Vue component which is responsible for rendering the SVG icon dynamically based on a prop value, for example, the name of the icon. Below is the example of the Vue icon component which renders an SVG mono-icon (an icon containing only one element, e.g. path)

To use this component one should provide the name, like <SvgPathIcon name="shop-1" /> which match a key from the icons' object in the example.

Of course, this is an example of a very simplified scenario which can be improved both from the feature and optimization side, e.g. loading the SVG paths as JSON via AJAX request.

I hope this might help you to develop your own SVG icon solutions. And if you want to run a demo locally take a look on the GitHub repo https://github.com/AndrejsAbrickis/vue-svg-icons

If you found this post useful and would like to read more about random web development topics, just clap for this article or drop a comment here. As always you can find me on Twitter@andrejsabrickis

This article, the content, and opinions expressed on Medium are my own. But as I work for one of the leading P2P loans marketplaces Mintos.com I would like to use this last line to promote that we are hiring. Including the Growth Engineering team, which I am leading.

You can see all list of the open positions on our Workable board. And feel free to contact me directly if you find something interesting in the list or would like to recommend someone you know.

Cheers!

--

--