Sasha Zoria
Sasha Zoria

Reputation: 771

Toggle active class Vue js

How to toggle active class, i.e. if i clicked on the element, an active class should be added to this item and removed from another.

<th @click="sort('campaign')" class="initial" :class="{active: isActive}">Campaign</th> // here i am toggling class
<th @click="sort('time')" class="initial" :class="{active: isActive}">Time</th>
<th @click="sort('views')" class="initial" :class="{active: isActive}">Views</th>
<th @click="sort('visitors')" class="initial" :class="{active: isActive}">Visitors</th>
<th @click="sort('ctr')" class="initial" :class="{active: isActive}">CTR</th>
<th @click="sort('cpc')" class="initial" :class="{active: isActive}">CPC</th>
<th @click="sort('cpv')" class="initial" :class="{active: isActive}">CPV</th>
<th @click="sort('cpm')" class="initial" :class="{active: isActive}">CPM</th>
<th @click="sort('status')" class="initial" :class="{active: isActive}">Status</th>

data(){
  return{
    isActive: false
   }
}

sort(s) {
  //if s == current sort, reverse
  this.isActive = !this.isActive;
  if(s === this.currentSort) {
  this.currentSortDir = this.currentSortDir==='asc'?'desc':'asc';}
  this.currentSort = s;
}

When i am clicking, class toggles on all items. Maybe i should make a component so that it has a local state.

Upvotes: 2

Views: 1329

Answers (2)

Eden M
Eden M

Reputation: 171

Thanks! working for me . and for test you can add css :

.active {
  color: rgb(150, 12, 12);
}

Upvotes: 0

dziraf
dziraf

Reputation: 3653

You have to link your element with current sort property. From what I see you probably didn't provide whole component code (can't see currentSort anywhere except it being used), but it's doable considering currentSort holds sorting type's name:

<th @click="sort('campaign')" class="initial" :class="{active: isActive}">Campaign</th>

change to:

<th @click="sort('campaign')" class="initial" :class="{active: currentSort === 'campaign'}">Campaign</th>

And this should be enough, isActive is now not needed. However, you would have to hard code this in all your ths. A better solution would be to create properties called sortingTypes and activeIndex:

data() {
  return {
    ...
    sortingTypes: ['campaign', 'time', 'view', 'etc'],
    activeIndex: null
  }
}

Then change your template a bit:

<th v-for="(sortType, index) in sortingTypes" @click="sort(sortType, index)" class="initial" :class="{active: index === activeIndex}">{{sortType}}</th>

and your sort method to:

sort(s, index) {
  this.activeIndex = index;
  if(s === this.currentSort) {
  this.currentSortDir = this.currentSortDir==='asc'?'desc':'asc';}
  this.currentSort = s;
}

Upvotes: 1

Related Questions