2

Please see the code

<div  v-for="msg in leftMsg">
   div v-if="msg.last_sender"   @click.prevent="loadMsg(msg)">
    <tr :class="['active',{ 'seens' : !msg.seen, 'selected':msg.isActive}]">
      // some html
    </tr>
   </div>
</div>

loadMsg(obj){
    obj.isActive = !obj.isActive;
}

The problem is, it is adding selected class properly but when I click another item it adds selected but doesn't remove the old one. How can I keep only the most recent clicked item selected?

Thank you.

2 Answers 2

3

Add a data property outside of the msg objects and use that to track the active message.

data(){
  return {
    activeMessage: null,
    ...
  }
}

Then in your template, set the activeMessage.

<div  v-for="msg in leftMsg">
   <div v-if="msg.last_sender" @click.prevent="activeMessage = msg">
    <tr :class="['active',{ 'seens' : !msg.seen, 'selected': msg === activeMessage}]">
      // some html
    </tr>
   </div>
</div>

The key parts I changed here are @click.prevent="activeMessage = msg" and 'selected': msg === activeMessage. This will set activeMessage to the clicked message, and then the selected class will be applied to the activeMessage and will only apply to the activeMessage.

I would also note that it's strange that you have a tr element nested inside div. I assume it was just because of your example, but that's not technically valid HTML.

Sign up to request clarification or add additional context in comments.

Comments

0

I have solved this issue using a for loop. I thought it may help some other. In order to remove the all other previous active classes all you need to run a for loop and make them false and then assign active=true to the newest one.

Here is the code that may help

       // make all other selected class false first
            for(let i=0; i<this.leftMsg.length; i++){
                    this.leftMsg[i].isActive=false;

             }
           /*now making the newest one active*/
            obj.isActive = true;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.