javascript - VueJS 在 v-for 中只选择一个元素
问题描述
我正在使用 Vue v2
我正在尝试仅更改所选元素的属性。看,当点击后响应被标记时,它应该变成红色,并带有“取消标记”的文字。反之亦然:如果再次单击该按钮(现在会显示“取消标记”),它应该变为绿色并且文本将是“标记”。唉,它有效....不过,我的代码将更改应用于 v-for; 中的每个元素;我只希望这发生在选定的元素上。
我曾考虑过使用组件来检查是否有变化,但首先我想看看是否有解决方案。任何帮助将不胜感激
这是我的代码:
<div class="search-results">
<div class="activity-box-w" v-for="user in users">
<div class="box">
<div class="avatar" :style="{ 'background-image': 'url(' + user.customer.profile_picture + ')' }">
</div>
<div class="info">
<div class="role">
@{{ '@' + user.username }}
</div>
<div>
<div>
<p class="title">@{{ user.customer.name }}
@{{user.customer.lastname}}
</p>
</div>
</div>
</div>
<div class="time">
<input type="button" class="btn btn-sm btn-primary" v-on:click.prevent="markUser(user)" v-model="text"
v-bind:class="[{'green-border':notMarked}, {'red-border':marked}]" v-cloak v-if="!action"
:disabled="action"></input>
</div>
</div>
</div>
现在为脚本:
new Vue({
el: '#engage-panel',
data: {
users: [],
mark: {'id' : '', 'marks' : ''},
text: 'Mark', //Migth change to Unmark later on
action: false,
marked: null,
notMarked: null,
},
methods:
{
markUser: function(user){
this.mark.id = user.id;
this.action= true;
Vue.http.headers.common['X-CSRF-TOKEN'] = $('meta[name="csrf-token"]').attr('content');
this.$http.put('/mark/user', this.mark).then(response => {
if(response.body === "marked")
{
this.mark.marks="true";
this.text = 'Unmark';
this.marked= true;
this.notMarked= false;
this.action= false;
}else{
this.mark.marks="false";
this.text = 'Mark';
this.marked= false;
this.notMarked= true;
this.action= false;
}
}).catch(e => {
this.action= false;
});
}
}
解决方案
$event.target
如果您只需要切换 css 类,则
可以使用on click。在这里摆弄
但是确实,如果用户具有类似的状态会更容易marked = true/false
,例如,您只需要绑定类,例如:
<input :class="{ 'green-border': user.marked, 'red-border': !user.marked }">
推荐阅读
- javascript - 当新视频以模态开始时停止播放其他 Youtube 视频
- r - (anti) 基于部分匹配的join
- python - python 3.9 需要 Microsoft Visual C++ 14.0 或更高版本吗?
- php - PHP如何从特定键输出字符串
- r - 在 `geom_bar()` 中找不到对象
- android - 如何使用 grep 从 Android 历史文件中仅检索 http?
- c++ - 是否允许将移动的对象作为 const 左值引用返回?
- javascript - 我怎么知道我的计数器是否已经达到限制?
- python - 如何使用熊猫制作条形图
- bash - 查找数组中某个元素的出现