Selecting specific element in vue 2 inside v-for l

2019-07-10 17:00发布

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.

标签: vue.js vuejs2
2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-07-10 17:38

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;
查看更多
我只想做你的唯一
3楼-- · 2019-07-10 17:45

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.

查看更多
登录 后发表回答