My Journey

Dynamic Class and Style Binding in Vue.js

February 05, 2022

At times, we need to add/remove CSS styles and classes conditionally. With Vue.js, this comes super handy.

We use the v-bind:class directive and pass the object with dynamic classes that we want to apply.

Class Binding

<template>
    <div class="static-class" :class="{'dynamic-class': addDynamicClass}" >
</template>
<script>
export default {
    data() {
        return {
            addDynamicClass: true
        }
    }
}
</script>

I’ve set addDynamicClass data property to true by default and it will be rendered as below

<div class="static-class dynamic-class" > Dynamic class added</div>

The dynamic class object can also be returned from a computed property

<template>
    <div class="static-class" :class="dynamicClass" > Dynamic class added </div>
</template>

<script>
export default {
    data(){}
    computed: {
        dynamicClass() {
            return {
                "dynamic-class" : this.addDynamicClass
            }
        }
    }
}
</script>

If we don’t want to use the object syntax, we can also pass an array of classes as follows

<template>
    <div :class=[dynamicClass] >Dynamic classes </div>
</tempate>

<script>
export default {
    data() {
        return {
            addDynamicClass: 'text-danger'
        }
    }
}
</script>

Style Binding

Style binding is also very similar to class binding,

<template>
    <div :style={color: dynamicStyle} >Dynamic style added </div>
</template>

<script>
export default {
    data() {
        return {
            addDynamicStyle: 'red'
        }
    }
}
</script>

To keep the template cleaner, we can also bind the style object

<template>
    <div :style="dynamicStyle" >Dynamic style added </div>
</template>

<script>
export default {
    data() {
        return {
            addDynamicStyle: {
                color: 'red'
            }
        }
    }
}
</script>

πŸ“ Thoughts by Zahid Jabbar.
A developer.

πŸ‘‹ Say hi