Conditionally Style SVGs The  Vue Way

Conditionally Style SVGs The Vue Way

Conditionally Style SVGs The Vue Way

Using Style And Class Binding In Vuejs


Introduction

In this article, we will cover how to conditionally style SVGs elements in a Vuejs application using the v-bind and v-class attribute provided by Vue

Preview

Here is a demo of what we are going to achieve. On click of the SVG, we are going to change the style using the style and class binding provided by Vuejs

Demo

Demo

Setup

First, let’s initialize a Vue project using the Vue CLI. Navigate to a directory on your computer and run the following command in your terminal.

vue create svg

After successfully creating the project, navigate to the directory and start the development server using the following command

npm run serve

Getting Started

Next, let’s download an SVG from Flaticon

Let’s create a component called svg.vue, and add our SVG to our Vue template with the following

We can conditionally bind our SVG to have a certain style using the style or the class binding. First, let’s use the class binding

Class Binding

To conditionally change the color of our SVG, we need to create a property in our data object that has a boolean value. Then, we bind the fill property in our SVG to has a particular color when the object in our state is true or false.

Conditionally bind SVG

Let’s bind the fill property in our SVG and add the following conditions

Conditional styling of SVG

What we’ve done here is set the fill of our SVG to be red when “isLiked” is true and black when it is false using a ternary operator.

Next, let’s create a method to toggle the fill/color of our SVG when it is clicked

Method to toggle the fill of the SVG when clicked

Add the “toggleSVG ” method as a click event listener to the SVG to toggle the state of the isLiked property. This will toggle the fill of our SVG.

Click event listener to toggle the fill of SVG when clicked

Style Binding

We can also achieve this using the style binding, where we use the v-bind:style attribute to set a certain style to be applied to our element (in this case the fill CSS property) and we can also manipulate it with a method

v-bind:style to conditionally style SVG Image for post

Now, we need to toggle the state of our SVG using the toggleSVG method we’ve created. But, we need to modify the method so it can achieve what we want.

This method will perform some logic using the ternary operator if the

click event to toggle SVG fill using the conditional ternary operator

There you have it, you can manipulate SVGs in a Vuejs application by changing the fill color. This is not limited to the fill color alone, you can manipulate the stroke and the width of the stroke using the v-bind:class and :style attribute.

Here is a link to the source code. Feel free to experiment with it.

If you find this helpful, give this article some thumbs up and follow me on Twitter