Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally adding a CSS class in Vue

Tags:

vue.js

Just started with Vue so I can't get this simple thing working. All I'm trying to do is toggle a class based on a condition.

<button type="button" 
        class="btn dropdown-toggle" 
        v-bind:class="{ btn-default: (search.category != 'all') }">
    {{ filterCategoryText || 'Category' }}
</button>
like image 846
eozzy Avatar asked Feb 14 '18 05:02

eozzy


People also ask

How do I add CSS to Vue?

In Vue. js, we can add an inline style to our element by binding the style attribute in the HTML tag. For reference, :style is shorthand for v-bind:style . Inline styling can be done in two ways: using object syntax or array syntax.

How do I add dynamic classes to Vue?

Adding a dynamic class name is as simple as adding the prop :class="classname" to your component. Whatever classname evaluates to will be the class name that is added to your component. Join 11,067 other Vue devs and get exclusive tips and insights delivered straight to your inbox, every week.


2 Answers

Firstly, as you discovered, you should probably remove the duplicate class definition. You can mix static and dynamic classes in the bound class definition. (If you leave the duplicate there it still works, though)

Then, you have the choice...

Object syntax

// property names will be in the class list if their values are truthy
:class="{ 
    'btn-default': search.category != "all", 
    'btn' : true, 
    'dropdown-toggle' : true 
}"

Array syntax

// an item in the array becomes a class in the class list
:class="[
    search.category != 'all' ? 'btn-default':'',
    'btn',
    'dropdown-toggle'
]"

Simple expression

// if you only have one item, just use a simple expression
:class="search.category != 'all' ? 'btn-default':''"

Docs are here

like image 50
bbsimonbb Avatar answered Oct 02 '22 12:10

bbsimonbb


Figured it:

<button type="button" 
        :class="[(search.category) ? '' : 'btn-default', 'btn dropdown-toggle']"
    {{ filterCategoryText || 'Category' }}
</button>
like image 39
eozzy Avatar answered Oct 02 '22 12:10

eozzy