首页 > 解决方案 > 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;
                });
    }

}

标签: javascriptarraysvue.jsvuejs2

解决方案


$event.target如果您只需要切换 css 类,则 可以使用on click。在这里摆弄

但是确实,如果用户具有类似的状态会更容易marked = true/false,例如,您只需要绑定类,例如:

<input :class="{ 'green-border': user.marked, 'red-border': !user.marked }">

推荐阅读