在 v-for 循环中选择 vue 2 中的特定元素 [英] Selecting specific element in vue 2 inside v-for loop

查看:38
本文介绍了在 v-for 循环中选择 vue 2 中的特定元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请看代码

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

加载消息(对象){obj.isActive = !obj.isActive;}

问题是,它正确添加了选定的类,但是当我单击另一个项目时,它添加了选定的但不会删除旧的.如何只选择最近点击的项目?

谢谢.

解决方案

msg 对象之外添加数据属性,并使用它来跟踪活动消息.

data(){返回 {活动消息:空,...}}

然后在您的模板中,设置 activeMessage.

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

我在这里更改的关键部分是 @click.prevent="activeMessage = msg"'selected': msg === activeMessage.这会将 activeMessage 设置为点击的消息,然后 selected 类将应用于 activeMessage 并且 only> 应用于 activeMessage.

我还注意到,您在 div 中嵌套了一个 tr 元素,这很奇怪.我认为这只是因为您的示例,但这在技术上不是有效的 HTML.

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.

解决方案

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.

这篇关于在 v-for 循环中选择 vue 2 中的特定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆