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?
The issue is that by binding a parent property to each instance, they share the parent's state and no longer represent their own state. One "vue-y" solution is to create a unique isActive state per instance via individual properties or an array of properties.
There are additional benefits to this type of unique representation. You may need to do more at a future date than just toggle a class on and off. You now have a way to identify active elements which will lead to a more scaleable application.
Keep in mind that at this point it would make more sense to encapsulate your behavior into a component so that you can reuse it with isolated scope.
I know the vuejs guide (Class and Style Bindings) uses data properties, but is this mandatory?
You can do that with java script like that:
Or as you mentioned you can create a component like that:
html: