How to Apply a Class Dynamically in Vue
Learn how to use Vue to dynamically apply classes based on conditions.
If you want to apply the class background-dark to an element when the isDark prop is true, and otherwise add the class background-light, here’s how you can achieve that in Vue.
You can use the :class directive along with a ternary operator in Vue.
1 | <template> |
In the above example, the :class directive is applied to the <div> element. Using [ isDark ? 'background-dark' : 'background-light' ], the class background-dark will be added if isDark is true, otherwise the class background-light will be added.
Make sure to add the “scoped” attribute to the <style> tag to limit the CSS to this component only.
Many thanks to Adam Wathan for suggesting this approach on the Tailwind Slack.
Tags: Vue.js, class binding, dynamic classes