'Apply multiple conditional classes in 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:
Solution 1:[1]
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 }
Solution 2:[2]
There are 2 syntaxes you can use:
- Object:
:class="{ position, direction }" - Array:
:class="[position ? 'position' : '', direction ? 'direction' : '']"
You can also make :class a string, but that's messy when you want to use conditionals for multiple classes. You could also do a computed property:
computed: {
myClass: function() {
return [position ? 'position' : '', direction ? 'direction' : ''].filter(c => !!c).join('');
}
}
See Conditional Classes in Vue for more examples.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mecograph |
| Solution 2 | mecograph |
