I am novice in VueJs and As I am trying to implement the basic toggle class functionality using v-bind property of VueJs in my Laravel project. I am not getting the value of variable className while rendering of the page. Please guide me where I am doing wrong. The code is given below:

<div id="root">
  <button type="button" v-bind:class="{'className':isLoading}" v-on:click="toggleClass">Toggle Me</button>
</div>

JavaScript is:

<script>
    var app = new Vue({
        el: '#root',
        data: {
            className:"color-red",
            isLoading:false
        },
        methods:{
            toggleClass(){
                this.isLoading=true;
                this.className="color-blue";
            }
        }
    })
</script>

Style is:

<style>
    .color-red{
        background-color:red;
    }
    .color-blue{
        background-color:blue;
    }
</style>
share|improve this question

You're mixing your approaches slightly. The main issue is in v-bind:class="{'className':isLoading}". This directive, the way you wrote it, toggles a class with the name "className" (literally that, not the value of the variable className) to your element if isLoading is true. If it's false, it doesn't assign any class.

Looking at your code, it seems you're actually trying to set two different classes depending on what the value of isLoading is. The easiest way to do this would be to use v-bind:class="isLoading ? 'color-red' : 'color-blue". Take a look at a working example here.

An even better solution that doesn't pollute your template with logic is to move that expression to a computed property, like this.

share|improve this answer

You can not have className as well as a variable name, as vue expects it as actual CSS class, documentation suggests one more way, have class object like following:

<script>
    var app = new Vue({
        el: '#root',
        data: {
            classObj:{ "color-red" : true } ,
            isLoading:false
        },
        methods:{
            toggleClass(){
                this.isLoading=true;
                this.classObj = { "color-blue" : true};
            }
        }
    })
</script>


<div id="root">
  <button type="button" v-bind:class="classObj" v-on:click="toggleClass">Toggle Me</button>
</div>
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.