Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply multiple conditional classes in Vue

Tags:

vue.js

I used style binding in Vue in this way:

v-bind:style="{'width': + width + 'px', 'left': + x + 'px', 'top': y + 'px'}"

When I required to bind multiple conditional classes, I used below syntax but it won't work!

v-bind:class="{(position)?position:'', (direction)?direction:''}"

Is there other way to apply multiple classes? Single class(without {}) works.

Here is the fiddle:

https://jsfiddle.net/kunjsharma/o0kL7myt/

like image 295
Kunj Avatar asked Jan 07 '20 10:01

Kunj


People also ask

How do I apply conditional condition in Vue?

To conditionally apply a CSS class at runtime, you can bind to a JavaScript object. To successfully complete this task, you must complete two steps. First, you must ensure that your CSS class is defined. Then, you create the class bindings in your template.

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.


Video Answer


2 Answers

The class binding expression in your template is invalid JavaScript syntax.

Did you mean to bind an array like this:

:class="[position, direction]"

So if position is 'right' and direction is 'rtl' then the element will have the classes right and rtl applied to it.

Binding an object is usually used when you have static class names that you want to apply conditionally based on some condition. Looking at your code, it doesn't seem like this is what you want to do.

For example, if you want to conditionally apply the static classes pressed and active based on some conditions, you can do this:

:class="{ pressed: pressedElement === el, active: !hidden }"

If pressedElement === el is true then the element will get the pressed class applied to it, likewise for active (I just made up some arbitrary expressions).

like image 75
Decade Moon Avatar answered Oct 15 '22 12:10

Decade Moon


The object based syntax for class definition is:

{
    className: isEnabled,
    anotherName: isOtherEnabled,
}

where the key (className) is the name of the class and the value (isEnabled) is whether it is enabled or not.

So in your case you might need { position: position, direction: direction }. You could even let javascript infer the key names for you { position, direction }.

If you instead want to set the class-name to be the value of the position and direction properties then you should instead use the array syntax: [position, direction]. You can also achieve this with the class syntax like so: { [position]: true, [direction]: true }

like image 33
James Coyle Avatar answered Oct 15 '22 10:10

James Coyle