提示:计算并选中复选框

时间:2018-10-18 12:23:26

标签: checkbox vue.js count checked

我想对vue做什么:

  • 计数选中的复选框
  • 将所有复选框设置为选中状态(或取消选中所有复选框)

这是一个非常简化的模型。真实的网站包含以下约束:

  • 复选框的数量更改。
  • 值始终是不同的。
  • 我不想将所有输入属性放入的数据部分 Vue

以下代码可以计算已选中复选框的数量。

<html>
  <body>
    <script src="https://unpkg.com/vue"></script>
    <div id="app">
      <input type="checkbox" name="abc" value=1 v-model="cch">
      <input type="checkbox" name="abc" value=2 v-model="cch">
      <br/>
      Count: {{cch.length}}
    </div>

    <script>
      new Vue({
          el: '#app',
          data: {
            cch: [],
          },
      })
    </script>
  </body>
</html>

以下代码选中所有复选框(当然,如果chk = false,则取消选中复选框):

<html>
  <body>
    <script src="https://unpkg.com/vue"></script>
    <div id="app">
      <input type="checkbox" name="abc" value=1 :checked="chk">
      <input type="checkbox" name="abc" value=2 :checked="chk">
      <br/>
      Checked: {{chk}}
    </div>

    <script>
      new Vue({
          el: '#app',
          data: {
            chk: true
          },
      })
    </script>
  </body>
</html>

似乎不可能在同一输入标签中使用:checked和v-model。 我该怎么办?


我添加了一个按钮,以选中所有复选框,并且更改了名称。问题仍然存在:计数工作正常,但是“全部”按钮没有任何作用。

<html>
  <body>
    <script src="https://unpkg.com/vue"></script>
    <div id="app">
      <input type="checkbox" name="abc1" value=1 v-model="cch" :checked="chk">
      <input type="checkbox" name="abc2" value=2 v-model="cch" :checked="chk">
      <br/>
      Count: {{cch.length}}
      <br/>
      <input type="button" @click="chk=!chk" value="all">
    </div>

    <script>
      new Vue({
          el: '#app',
          data: {
            cch: [],
            chk: true
          },
      })
    </script>
  </body>
</html>

1 个答案:

答案 0 :(得分:0)

您需要为每个复选框设置唯一的名称属性。这样,它们就可以在v模型中正常工作。

相关问题