Vue Snippets – Conditional Style Binding
Posted on: May 06, 2020 by Kelvin Gobo
A common use for data binding is to conditionally alter the classes and styling of an element. The snippet below shows how this can be achieved:
<template>
<div>
<p>Red</p>
<p :class="{'active': active}">Blue</p>
</div>
</template>
<script>
export default {
data() {
return {
active: true
};
}
};
</script>
<style lang="scss" scoped>
p {
color: red;
&.active {
color: blue;
}
}
</style>
By default, the <p>
tag is styled to have a red text color. However, <p>
tags with the .active
class get styled with a blue text. Since the data property active
is true, the .active
class is added to the second paragraph and when rendered, it’s text is blue.
Use Cases
- Dynamically applying styles
Share on social media
//