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.
<template>
<div :class="[ isDark ? 'background-dark' : 'background-light' ]">
<h1>{{ msg }}</h1>
</div>
</template>
<script>
export default {
props: {
isDark: Boolean
}
}
</script>
<style scoped>
.background-dark {
background-color: #000;
}
.background-light {
background-color: #fff;
}
</style>
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