VueJS Basics

VueJS: Binding To A Class

In a previous VueJS tutorial we learnt how you can bind to a HTML attribute such as title, in this tutorial we're going to go further with that concept and bind to the class attribute so we can change the styling of an element from the data changes in the application.

A good way of show an example of this is switching a notification box from successful to failure. For this we're going to use Twitter bootstrap CSS to change the styling of the notification box.

To create a successfully notification you need to use the following html.

<div class="alert alert-success">

</div>

To show a failed notification box you need to use the following html.

<div class="alert alert-danger">

</div>

In the example we need to have a notification box and a button to switch the data to change the box from successful to error. To bind Vue data to the class attribute you need to use the directive v-bind, then we add a click event to the button by using v-on:click to switch the data and change the notification box.

<div id="app">
    <div class="alert" v-bind:class="{ 'alert-success': this.isSuccessful, 'alert-danger': this.isError }">
        <p>Display Bootstrap notification box</p>
    </div>

    <p><button v-on:click="switchClick">Switch Notification Box</button></p>
</div>

In the above example we have the notification box with a Vue bind on the class attribute, then we define the object for what we want to show. If this.isSuccessful is true then alert-success will be added to the class attribute, if this.isError is true then alert-danger is added to the class attribute.

On the click event of the button it will call the switchClick method. Therefore we now know what needs to be added to the Vue object.

<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script>
    var app = new Vue({
        el: '#app',
        data: {
            isSuccessful: true,
            isError: false
        },
        methods: {
            switchClick: function(){
                if(this.isSuccessful && !this.isError)
                {
                    this.isSuccessful = false;
                    this.isError = true;
                }
                else if(this.isError && !this.isSuccessful)
                {
                    this.isError = false;
                    this.isSuccessful = true;
                }
            }
        }
    })
</script>

For the click event the method switchClick will be called here we will switch the booleans of both isSuccessful and isError. This will toggle the class of the notification box changing it from successful to an error notification.

View the demo to see this in action.

Demo

Back to top

View Demo

Members Download