Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuejs dynamically toggle class is not working in Laravel Blade Template

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>
like image 426
abhishekvbajaj Avatar asked Dec 29 '16 07:12

abhishekvbajaj


1 Answers

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.

like image 199
mzgajner Avatar answered Oct 23 '22 14:10

mzgajner