vue的一个全选和反选

Vue 实现全选、反选的方法如下:

  1. 在 Vue 的 data 选项中添加一个全局变量 selectAll,并将其初始化为 false

  2. 在表格头部添加一个复选框用于全选/反选,绑定点击事件 checkAll

<th><input type="checkbox" v-model="selectAll" @click="checkAll"></th>

3.给每一行的复选框绑定 isChecked 变量来标记该行是否被选中。然后在全选/反选时遍历所有行,修改它们的 isChecked 状态。

<tr v-for="item in items">
  <td><input type="checkbox" v-model="item.isChecked"></td>
</tr>

4.在底部显示已选数量和取消选中按钮。

<p>已选择 {{ checkedCount }} 项</p>
<button @click="clearSelection">取消选中</button>

5.

在 Vue 的 methods 选项中添加以下方法:

  • checkAll():全选或反选

  • checkAll() {
      this.selectAll = !this.selectAll;
      for (let item of this.items) {
        item.isChecked = this.selectAll;
      }
    }
    

  • clearSelection():取消选中

  • clearSelection() {
      for (let item of this.items) {
        item.isChecked = false;
      }
    }
    

  • checkedCount:计算当前有多少项被选中。

  • computed: {
      checkedCount() {
        return this.items.filter(item => item.isChecked).length;
      }
    }
    

    完整代码

  • <template>
      <div>
        <table>
          <thead>
            <tr>
              <th><input type="checkbox" v-model="selectAll" @click="checkAll"></th>
              <th>ID</th>
              <th>Name</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in items">
              <td><input type="checkbox" v-model="item.isChecked"></td>
              <td>{{ item.id }}</td>
              <td>{{ item.name }}</td>
            </tr>
          </tbody>
        </table>
        <p>已选择 {{ checkedCount }} 项</p>
        <button @click="clearSelection">取消选中</button>
      </div>
    </template>
    
    <script>
    export default {
      data() {
        return {
          selectAll: false,
          items: [
            { id: 1, name: 'Apple', isChecked: false },
            { id: 2, name: 'Banana', isChecked: false },
            { id: 3, name: 'Orange', isChecked: false }
          ]
        };
      },
    
      methods: {
        checkAll() {
          this.selectAll = !this.selectAll;
          for (let item of this.items) {
            item.isChecked = this.selectAll;
          }
        },
    
        clearSelection() {
          for (let item of this.items) {
            item.isChecked = false;
          }
        }
      },
    
      computed: {
        checkedCount() {
          return this.items.filter(item => item.isChecked).length;
        }
      }
    };
    </script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

筱闯~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值