When it comes to CSS class binding in Vue.js you have multiple options. You could just write just styles and classes inline, or you can use computed properties or even methods to return your desired styles and classes based on events.
the computed property approach:
As an example, we are going to create a navigation component. Initially, the navigation is hidden and only visible if we click the
Show Navigation Button.
Obviously, I could use
v-show to hide and show the navigation but for this example, I’ve decided against it.
( For further experimentation: https://codesandbox.io/s/q76wznyx46 )
As you see I pass a computed property called
navState as a class to my navigation. Inside the
navState property, I check if the navigation is active or not, so whether the button was clicked or not.
If the user clicked the button
nav--active gets rendered as a class if not
nav--inactive gets rendered.
Obviously, I could do this without the
navState property. Then my code would look like this:
But in my opinion, it is much cleaner an easier to read with a computed property. That way you can write your logic inside the logic part of the component rather than in the markup part.
the method approach
For this example, we’re creating a list with a
v-for loop. We want to use a grey background-color for every even item in the list. Therefore we’re using a method to determine whether the current item-index is odd or even.
With this approach, you can render your list or whatever based on what's inside of it. Let's say you have a list consisting of objects. Some are just strings, others are links. And you want to render the links in a different style than the strings. You could pass the whole object to a function that checks if it’s a link or not and render the link with a different style.
(If you want to play around with this a little more: https://codesandbox.io/s/4w4qpm2mj0 )
I hope you found that article helpful, and if you did, give me a clap or hit me up on Twitter.
In the end, it’s up to you which of the various possibilities you use to render conditional classes and styles. But computed properties and methods are definitely my favorite options.
What is your favorite way of rendering conditional classes? Let me know in the comments below.