Learn the basics of binding classes in Vue.js.
Vue.js allows you to easily manipulate HTML elements classes. We can use v-bind
with class attribute to change it.
Vue.js v-bind syntax
<!-- full syntax -->
<div v-bind:class="{ active: isActive }"></div>
<!-- shorthand -->
<div :class="{ active: isActive }"></div>
In this example you can see that an object can be passed to v-bind:class
or just :clas
s to dynamically toggle classes.
If the object isActive
is true the above code will render:
<div class="active"></div>
v-bind class examples in Vue.js
You can send multiple objects.
new Vue({
el: "#app",
data: {
isActive: false,
isLoading: true
}
})
<div id="app">
<div :class="{ 'active': isActive, 'loading': isLoading }"></div>
</div>
Will render to:
<div class="loading"></div>
Render classes conditionally in Vue.js
You can also toggle a class conditionally using a conditional (ternary) operator.
new Vue({
el: "#app",
data: {
isLoading: true
}
})
<div :class="[ isLoading ? 'loading' : 'loaded' ]"></div>
Will render to:
<div class="loaded"></div>
Please note the square brackets in the example above.
These are just a few examples to show you the very basic ways to implement classes using v-bind
. There are loads of other ways you can toggle classes in Vue.js e.g. using computed properties, arrays etc.
You can even pass classes to custom components as parameters.
If you find this post useful, please let me know in the comments below.
Cheers,
Renat Galyamov
Want to share this with your friends?
👉renatello.com/vue-js-classes
PS: Make sure you check other Vue.js tutorials.