element-ui checkbox基础多选(绑定后台json对象值)

首先申明看你需求的数据格式是怎样的
如果是json数组的如:

const cityOptions = ['上海', '北京', '广州', '深圳']

那么可以直接看element-ui的官方链接的写法
https://element.eleme.cn/#/zh-CN/component/checkbox
但我们实际项目开发中大部分都是json数组而element-ui的官方文档中没有给出详细的操作流程
直接上码
html部分:

    <div>
      <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
      <el-checkbox-group v-model="data" @change="handledataChange">
        <el-checkbox v-for="(value,key) in datas" :key="key" :label="value.key">{{ value.name }}</el-checkbox>
      </el-checkbox-group>
    </div>

data部分:

      datas: [{ key: 1, name: '小明' }, { key: 2, name: '小王' }, 
      { key: 3, name: '小张' }, { key: 4, name: '小刘' }, 
      { key: 5, name: '小李' }, { key: 6, name: '小邓' }], // json对象数据
      checkAll: false, // 全选状态
      data: [],
      isIndeterminate: true //indeterminate 属性用以表示 checkbox 的不确定状态,一般用于实现全选的效果

method中js部分:

   //全选
    handleCheckAllChange(val) {
      // 绑定json对象时
      this.checkAll = !!this.checkAll //判断全选
      const checked = this.datas.map(function(item) { return item.key }) //通过使用map绑定要去得的值(键)我这里取key
      this.data = this.checkAll ? checked : [] // 是否被选中
      this.isIndeterminate = false
      console.log(this.data)
      // 绑定纯json数组
      // this.data = val ? this.datas : []
      // this.isIndeterminate = false
    },
    // 非全选
    handledataChange(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.datas.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.datas.length // 根据选中的数量定义全选的状态
      console.log(value)
    },

handleCheckAllChangehandledataChange方法中的输出是一个json数组 数据是被选中的值 我这边因为设置**:label=“value.key”** 所以输出的也是key的值
在这里插入图片描述
非全选时:
在这里插入图片描述
我的数据格式:
在这里插入图片描述
源码链接:
https://download.csdn.net/download/qq_41193701/12049212

猜你喜欢

转载自blog.csdn.net/qq_41193701/article/details/103685391
今日推荐