Header Ads

Learn Vue.js Step By Step: Dynamic Styles and Classes


In our previous lesson we've learned about Vue's Event Listeners. In this lesson we will be talking about Dynamic Styles and Classes. It is common in our application that we are going to change the attributes of an element like classes and styles dynamically. In Vue we can achieve that using the v-bind directive.

Let's say we want to change the color of a div tag based on the user selection.
<!DOCTYPE html>
<html>
<head>
<title>Learn Vue.js Step By Step: Dynamic Styles and Classes</title>
<style>
    .box {width: 300px;height: 200px;}
    .bg-red {background-color: #f00;}
    .bg-blue {background-color: #00f;}
    .bg-green {background-color: #0f0;}
</style>
</head>
<body>
    <div id="app">
        <div class="box" v-bind:class="bg"></div>
        <ul>
            <li>
                <input type="radio" value="bg-red" v-model="bg"> Red
            </li>
            <li>
                <input type="radio" value="bg-green" v-model="bg"> Green
            </li>
            <li>
                <input type="radio" value="bg-blue" v-model="bg"> Blue
            </li>
        </ul>
    </div>

    <script src="https://unpkg.com/vue"></script>
    <script>
        new Vue({
            el: '#app',
            data: {
                bg: 'bg-red'
            }
        })
    </script>
</body>
</html>
After running this code in the browser you will noticed that Vue automatically append the value of bg into the class attribute, provided there is an existing class attribute otherwise Vue will create one for you.

Vue also provide a shorthand syntax for v-bind which is : like so:
<div class="box" :class="bg"></div>

You can also use object syntax like so:
<div class="box" :class="{ active: isActive }"></div>
The above syntax means that if the value of the isActive data property is truthy then the active class will be appended to the element.

That's all for this lesson, for more information about this topic please refer to the official documentation. As always if you have any questions please don't hesitate to write it down in the comment section below and see you in the next lesson. Stay tuned!

Previous: Event ListenersNext: Computed Properties and Watchers


No comments