I have some li elements in a v-for cicle. I need to select more then one at the same time and, if already selected, remove active class.
My script works if I select the items in order: from first to last (to select items), from last to first (to deselect items). Please help me.
var example1 = new Vue({
el: '#example-1',
data: {
tags: ['tag-1', 'tag-2', 'tag-3', 'tag-4'],
activeTag: [],
},
methods: {
onTagClick: function(i) {
if ( this.activeTag.includes(i) ) {
console.log('Delete');
const index = this.activeTag.indexOf(i);
if ( index > -1 ) {
this.activeTag.splice(index, 1);
}
} else {
console.log('Add');
this.activeTag.push(i);
}
console.log(`activeTag[i]: ${this.activeTag}`);
}
}
})
li {
display: inline-block;
padding: 8px 10px;
margin-right: 0.5rem;
}
a {
color: #000;
text-decoration: none;
}
li.active>a{
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.js"></script>
<div id="example-1">
<ul v-if="tags">
<li v-for="(tag, i) in tags" :key="i" :class="{active: activeTag[i] === i}">
<a @click="onTagClick(i)" href="javascript:void(0)">{{ tag }}</a>
</li>
</ul>
</div>