选中嵌套循环中的所有复选框

时间:2019-05-25 22:49:33

标签: javascript vue.js

我在下面嵌套了以下for循环。通常情况下,格式是一个复选框网格,下面是玩家,顶部是团队。每个球员都有一行,每个团队都有一列,每个“单元”都有一个复选框。我可以选择和取消选择各个复选框。如何检查每一列的所有复选框? checkedPlayerTeams是一个已经检查过的PlayerTeam数组。

如您所见,我在第一个循环中添加了一个“全选”复选框,但是checkedPlayerItems不会使用正确的“值”进行更新。我应该采取其他方法吗?您还需要其他东西吗?

<div class="flex-row grid_body">
  <div class="card" v-for="team in teams" :key="team.id">
    <input
      :id="'team_' + team.id"
      type="checkbox"
      v-model="checkedPlayerTeams"
      :value="team.id"
    >

    <div class="options">
      <ul>
        <li v-for="player in players">
          <div>
             <input
               :id="'team_' + team.id + '_player_'+ player.player_id"
               type="checkbox"
               v-model="checkedPlayerTeams"
               :value="{team_id: team.id, player_id: player.player_id, status: team.status}"
             >
             <label :for="'team_' + team.id + '_player_'+ player.player_id" class="flexbox flex-label no-bg">
           <span></span>
            </label>
          </div>
        </li>
      </ul>
    </div>
  </div>
</div>

checkedPlayerTeams的数据结构如下:

[{“ player_id”:2,“ team_id”:1,“ status”:true} .....等。

1 个答案:

答案 0 :(得分:0)

我认为处理此问题的最简单方法是将选中的值保留在每个玩家中。所以应该像这样:

data: () => ({
  teams: [
    {
      id: 1,
      players: [
        { id: 11, status: false },
        { id: 12, status: false }
      ]
    },
    {
      id: 2,
      players: [
        { id: 21, status: false },
        { id: 22, status: false },
        { id: 23, status: false }
      ]
    }
  ]
})
<div v-for="team in teams" :key="team.id">
  <div v-for="player in team.players" :key="player.id">
    <input type="checkbox" v-model="player.status">
  </div>
</div>

对于选择团队中的所有球员,您可以侦听变更事件,然后调用某些方法作为传递团队ID和检查值,例如:

<label>
  <input
    type="checkbox"
    @change="selectTeam(team.id, $event.target.checked)"
  >
  <span>Select All</span>
</label>
selectTeam(teamId, checked) {
  let team = this.teams.find(team => team.id === teamId);
  team.players.forEach(player => {
    player.status = checked;
  });
}

要保持“全选”复选框值响应玩家状态更改,可以使用如下观察者:

teams: {
  handler() {
    this.teams.forEach((team, teamIndex) => {
      let checked = true;
      team.players.forEach(player => {
        checked = checked && player.status;
      });
      this.$refs.selectTeams[teamIndex].checked = checked;
    });
  },
  deep: true
}

Example