Vue+element-ui 多选框遍历数组+批量删除数据

多选框可以删除一条或多条数据

<template>
    <div>
      <el-button type="danger" size="small" @click="allRemove">删除</el-button>
      <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
      <div style="margin: 15px 0;"></div>
      <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
      <el-checkbox v-for="url in urls" :label="url.id" :key="url.id">{{url.id}}</el-checkbox>
      </el-checkbox-group>
    </div>
</template>

js部分

export default {
    data() {
      return {
        urls: [],
        checkAll: false,
        checkedCities: [],
        isIndeterminate: true
      }
    },
    methods: {
      //请求数据事件
      getList() {
       //get你的数据接口
        let action = '';
        this.$get(action, {
            action: action
          })
          .then(res => {
            this.urls = res.data;
          })
      },


      //监听全选按钮变化
      handleCheckAllChange(val) {
        //遍历数组获取到所有id
        let checked = this.urls.map(item => {
          return item.id
        })
        /*定义一个变量,让删除事件获取到自定义变量的值
        */
        this.dval = val;
        //当true的时候返回有数据的数组,false的时候返回空数组
        this.checkedCities = val ? checked : [];
        this.isIndeterminate = false;
      },


      //监听单选框按钮变化
      handleCheckedCitiesChange(value) {
        this.remove = value
        let checkedCount = value.length;
        this.checkAll = checkedCount === this.urls.length;
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.urls.length;

      },

      //删除数据点击事件
      allRemove() {
          console.log(this.remove);
          console.log(this.checkedCities);
          let ids = '';
          //这里你批量删除的接口
          let action = '';
          //获取监听值
          if (this.dval == true) {
            //全选
            ids = this.checkedCities;
          } else {
            //单选一个或选择多个
            ids = this.remove;
          }
          this.$post(action, {
            action: action,
            ids: ids,
          }).then(res => {
            if (res.ret == 200) {
                this.$message.success('成功')
                //成功的话就重新拉取数据
                this.getList();
            } else {
              this.$message.error(res.msg);
            }
          }).catch(err => {
            console.log(err);
          });
      },
    },


    created() {
      this.getList();
    },
  }

</script>
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值