I have seen several examples of how to toggle a class in Vue.js like this:
new Vue({ el: "#app", data: { isActive: false } });
.demo { width: 100px; height: 100px; background-color: red; display: inline-block; } .active { border: #000 solid 3px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.7/vue.js"></script> <div id="app"> <div class="demo" @click="isActive = !isActive" :class="{active: isActive}"></div> </div>
Clicking the element toggles if it is active true or false and you are then toggling the class. This is fine, but doesn’t work when you have more elements that you also what to toggle and active class on and off like this:
new Vue({ el: "#app", data: { isActive: false } });
.demo { width: 100px; height: 100px; background-color: red; display: inline-block; } .active { border: #000 solid 3px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.7/vue.js"></script> <div id="app"> <div class="demo" @click="isActive = !isActive" :class="{active: isActive}"></div> <div class="demo" @click="isActive = !isActive" :class="{active: isActive}"></div> <div class="demo" @click="isActive = !isActive" :class="{active: isActive}"></div> </div>
Now we are toggling the same for all of them, even though we just want to toggle the individual element that was clicked.
I know in jQuery this would be very simple:
$('.demo').on('click', function() { $(this).toggleClass('active'); });
.demo { width: 100px; height: 100px; background-color: red; display: inline-block; } .active { border: #000 solid 3px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="app"> <div class="demo"></div> <div class="demo"></div> <div class="demo"></div> </div>
I have seen an example that required an entire component to be made that needed to be exported/imported just to scope the isActive property to that individual div, however that solution seems like a lot for such simple behavior. So what would be the simplest solution to toggling an .active class on/off of individual elements like my jQuery example?
Advertisement
Answer
You can do that with java script like that:
new Vue({ el: "#app", methods:{ setActive(event){ event.target.classList.toggle("active"); } } });
.demo { width: 100px; height: 100px; background-color: red; display: inline-block; } .active { border: #000 solid 3px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.7/vue.js"></script> <div id="app"> <div class="demo" @click="setActive"></div> <div class="demo" @click="setActive"></div> <div class="demo" @click="setActive"></div> </div>
Or as you mentioned you can create a component like that:
Vue.component('test-component',{ template: `<div class="demo" @click="isActive = !isActive" :class="{active: isActive}"></div>`, data(){ return { isActive: false } } });
html:
<div id="app"> <test-component></test-component> <test-component></test-component> <test-component></test-component> </div>