4 ms·
Question: I used CSS utility classes for building components in VueJS. The problem I ran into was that I wanted to apply classes only when certain conditions ar
by tqkxzugoaupvwqr 7y ago
Question: I used CSS utility classes for building components in VueJS. The problem I ran into was that I wanted to apply classes only when certain conditions are met, i.e. style the component slightly differently based on its state. This caused me to check the condition repeatedly – once per class I want to apply. Is there a better way, e.g. applying all classes together after checking once?
TypeScript/JavaScript:
export default Vue.extend({
data() {
return {
isActive: false,
};
},
computed: {
componentClasses() {
return ["margin-4", "padding-3", {
"color-red": this.isActive,
"font-size-30": this.isActive,
"font-weight-700": this.isActive,
}];
}
}
});
- erikschoster 7y agoAdd a class called "active" or similar, and write your css to target the element when that class is present. .element.active { color: red; font-size: 30px; font-weight: 700; }
- aliveupstairs 7y agothe docs: https://vuejs.org/v2/guide/class-and-style.html#Binding-HTML-Classes https://vuejs.org/v2/guide/class-and-style.html#Binding-HTML... https://vuejs.org/v2/guide/class-and-style.html#Array-Syntax https://vuejs.org/v2/guide/class-and-style.html#Array-Syntax In your template: a) <div :class={active: isActive} /> b) <div :class="{isActive? 'active' : 'inactive' }"/>
- earthboundkid 7y agoB) is not valid. It needs to be wrapped in an Array, not an Object.
- malydok 7y agoWouldn't it be possible to do: `["margin-4", "padding-3", ...(this.isActive ? ["color-red", "font-size-30", "font-weight-700"] : [])]`