简体   繁体   中英

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>

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 .

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM