Vue Conditional Class Binding

774 Views Asked by At

I am trying to dynamically render class based off actionTypeCreate. This is a method that simply returns a boolean value based off the prop actionType that is passed. I am triggering this method on the mounted hook and confirmed it is returning properly.

Now I am trying to return the class value of 'col-md-4' if actionTypeCreate. If not actionTypeCreate I want to return the class 'col-md-6'.

This is what I have but it is not working:

:class="{toggleActionType : 'col-md-4' ? 'col-md-6'}"

I tried to reference this existing question, but I did not get it.

3

There are 3 best solutions below

0
On BEST ANSWER

According to the Vue documentation itself you can do it in two ways. First, you can use Array Syntax and this is broadly used to apply a list of classes.

Array Syntax

:class="[toggleActionType ? 'col-md-4' : 'col-md-6']"

Or you can do it as normal by Object Syntax but it does not accept ternary operations, so you have to do it this way:

Object Syntax

:class="{'col-md-4' : toggleActionType , 'col-md-6' : !toggleActionType}"
0
On

Try this:

:class="[toggleActionType : 'col-md-4' ? 'col-md-6']"
0
On

You can do it as follows:

:class="{'col-md-4' : toggleActionType , 'col-md-6' : !toggleActionType }"