In Vue.js, change the value of a specific attribute for all elements of a data array
I am trying to switch a class open
to a list of items in v-repeat
. I only need one list item (the one that was recently clicked) to have a class open
.
The output has a "class" attribute, which is an empty string by default. I use this to set the class of list items to be v-repeat
like this:
<li v-repeat="dataSet"
v-on="click: toggleFunction(this)"
class="{{ class }}">
{{ itemContent }}
</li>
I use v-on="click: toggleFunction(this)"
for each element, which allows me to change the class for a specific element, but how do I change the class for all other elements?
My current click method:
toggleFunction: function(item) {
if (item.class == '') {
// code to remove the `open` class from all other items should go here.
item.class = 'open';
} else {
item.class = '';
}
}
I tried to use a regular jQuery function to mark up the classes: it removes the classes but doesn't change the attribute item.class
, so things get weird after the element is clicked more than once ...
I'm sure there must be an easy way to fix this, which I don't see, and having to set an attribute class
on the data itself feels hacky anyway (but I'll settle for any fix that works).
source to share
I just ran into the same problem. I am still learning Vue, but I have been doing this using the "v-class" directive. Using the v-class, anytime the active value is true for writing, it will automatically add the "open" class to the list item. Hope this JSFiddle helps.
<ul>
<li
v-repeat="people"
v-on="click: toggleActive(this)"
v-class="open: active">{{ name }}
</li>
</ul>
new Vue({
el: '#app',
data: {
people: [
{name: 'mike'},
{name: 'joe',active: true},
{name: 'tom'},
{name: 'mary'}
]
},
methods: {
toggleActive: function(person) {
// remove active from all people
this.people.forEach(function(person){
person.$set('active',false);
});
//set active to clicked person
person.$set('active',true);
}
}
});
source to share