srividya
srividya

Reputation: 81

VueJs set active class to the data coming from API, when one li element is clicked in V-for loop

I need to set active class to one of the many options, which is coming from API. Also the first option is active at first, and when user clicks it has to toggle. Below is my template :

<div @click="showTimezone">
        <span>{{defaultCountry}}</span>
    </div>
<div  id="timezone-menu" class="timezone-menu" v-show="showTimezone">
          <ul >
            <li class="country-menu-item" v-for="item in Options" :id="item.id" :key="item.abbrevation" @click="selectCountry(item)">
                {{ item.optionText }}
            </li>
          </ul>    
        </div>

I stored the data from API in Options array.

data() {
     return {
        defaultCountry: "CST",
        Options: [],
    }
   }

On the drop down, the CST will be by default Bold. On clicking other option, it should lose its style class and added to the other option which user clicked. Please help me out on how to do this. Will provide additional details if required.

Upvotes: 0

Views: 861

Answers (1)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

Add property called activeId to your data object and update it in the selectCountry method:

data() {
     return {
       defaultCountry: "CST",
       Options: [],
       activeId:-1
    }
    },
methods:{
  selectCountry(item){
    ...
    this.activeId=item.id;
  
  }
}

in the template add the class binding :

<li class="country-menu-item" :class="{'active':item.id===activeId}" v-for="item in Options" 

Upvotes: 1

Related Questions