Vuejs dynamically switches class, does not work in Blade Laravel template

I am new to VueJs and since I am trying to implement the basic functions of the toggle class using the v-bind VueJs property in my Laravel project. I do not get the value of the className variable when rendering the page. Please guide me where I am doing wrong. The code is below:

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

JavaScript:

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

Style:

 <style> .color-red{ background-color:red; } .color-blue{ background-color:blue; } </style> 
+5
source share
2 answers

You mix your approaches slightly. The main problem is v-bind:class="{'className':isLoading}" . This directive, as you wrote it, switches the class with the name "className" (literally this, not the value of the className variable) to your element if isLoading is true . If it is false , it does not assign any class.

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

An even better solution that does not pollute your template with logic is to move this expression into a computed property like this .

+1
source

You cannot have className , and also the name of the variable, since vue expects it as an actual CSS class, the documentation offers another way, have a class object, for example:

 <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> 
0
source

Source: https://habr.com/ru/post/1262015/


All Articles