简体   繁体   中英

VueJs set active class, when One li element is clicked in dropdown using V-for loop

I can't figure out how to set active class in dropdown options, using v-for loop and one of the option is bold by default. On clicking other option, the active class should be added to the other option, making the clicked option bold and vice versa.

<div id="jobAid-menu" class="dropdown-content" v-if="openTypeView"> 
        <ul> 
          <li class="type-li-item" v-for="item in help" :id="item.liId" :key="item.id" :class="item.class"  @click="changeHelpType(item)">
          <span>{{ item.name }}</span>
          </li>  
        </ul>
     </div>

And below is my JS Code,

data(){
    openTypeView: false,
    active_id: 1,
    help: [
             
            {
              name: "Users",
              id: 1,
              liId: 'g1',
              class: 'active',
            },
            {
              name: "Profile",
              id: 2,
              liId: 'g2',
              class: '',
            },
          ],
},
    methods:{
     changeHelpType:function(item){
     if(this.active_id===item.id){
                  this.help.find(item => item.id === this.active_id).class='';
                  this.help.find(item => item.id===id).class='active' ;
                  this.active_id =id;
                  }
    }
    }

CSS Styling

li {
 font-weight:normal;
}

li.active {
  font-weight:bolder;
}

Now By default the first object in help array is active. if I click on other li element in the dropdown it should become active and all other li element should lose active class. Can you please help me out on how to do this. I'm a newbie in VueJS, ignore my mistakes if any.

First your data option should be a function that returns an object, second use a computed property based on help property to add class field :

data(){
   return{
    openTypeView: false,
    active_id: 1,
    help: [
             
            {
              name: "Users",
              id: 1,
              liId: 'g1',
              class: 'active',
            },
            {
              name: "Profile",
              id: 2,
              liId: 'g2',
              class: '',
            },
          ],
  }
},
computed:{
   customHelp(){
      return this.help.map(item=>{
        item.class= this.active_id===item.id?'active':''
                  return item;
            })
   }
}

then loop through that computed property :

 <li class="type-li-item" v-for="item in customHelp" :id="item.liId" 

:key="item.id" :class="item.class"  @click="active_id=item.id">
          <span>{{ item.name }}</span>
 </li> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM