element-UI,根據後臺數據、動態生成el-checkbox-group,點擊提交獲取綁定checked項以及實現顯示默認checked項

<template>
  <div id="Demo">
    <el-form ref="form" label-width="100px">
      <el-form-item label="設備名稱">
       <div class="check-group" v-for="(item, index) in equipments" :key="index">
          <el-tag>{{item.menu}}</el-tag>
          <el-checkbox-group v-model="checkedEquipments[index]" @change="handleChange(item.id)"> {{checkedEquipments[index]}} <el-checkbox v-for="data in item.childMenu" :label="data.id" :key="data.menu"> {{data.menu}} </el-checkbox>
          </el-checkbox-group>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>
export default { data() { return { checkedEquipments: [], //隨意修改後的checked項(即要傳到後臺的變動數據)
        equipments: [   // 全部數據
 { id: '1', menu: '設備1', childMenu: [{ id: '1-1', menu: '暖通一' }, { id: '1-2', menu: '照明一' }, { id: '1-3', menu: '取暖一' }, { id: '1-4', menu: '應急一' } ] }, { id: '2', menu: '設備2', childMenu: [ { id: '2-1', menu: '暖通二' }, { id: '2-2', menu: '照明二' }, { id: '2-3', menu: '取暖二' }, { id: '2-4', menu: '應急二' } ] } ], checkEquip: [ //模擬後臺獲取的數據(各el-checkbox-group默認checked項)
 { id: '1', menu: '設備1', childMenu: [ { id: '1-1', menu: '暖通一' }, { id: '1-2', menu: '照明一' } ] }, { id: '2', menu: '設備2', childMenu: [] } ] }; }, methods: { handleChange () { this.checkEquipArr = [] let arr = this.checkedEquipments for (let i = 0; i < arr.length; i ++) { let equipment = arr[i] if (equipment.length > 0) { let obj = { id: this.equipments[i].id, equips: [] } for (let j = 0; j < equipment.length; j++) { obj.equips.push(equipment[j]) } this.checkEquipArr.push(obj) } } console.log(this.checkEquipArr); } }, created () { // 初始化默認選中狀態
      for (let i = 0; i < this.checkEquip.length; i++) { let checkArr = [] let item = this.checkEquip[i].childMenu if (item.length === 0) { this.checkedEquipments.push([]) }else { for (let j = 0; j < item.length; j ++) { checkArr.push(item[j].id) } this.checkedEquipments.push(checkArr) } } console.log(this.checkedEquipments); } };

每一個人的數據格式不同,可是實現邏輯都是同樣的。能夠做爲參考,稍微修改一下代碼實現符合本身的數據格式。數組

實現結果(動態生成 checkbox-group,而且設置默認checked項),具體v-model值,須要打印看咯ui

 

簡單點來講:this

就是根據你的數據生成一個二維數組,好比data是lists,那麼就是這樣寫了spa

data() { return { lists: [你的數據], checkList: [] } } 

 

<el-checkbox-group v-for="(power, index) in lists" v-model="checkList[index]">
              <el-checkbox  v-for="power in group.powers" :key="power.id" :label="power.id">{{power.name}}</el-checkbox>
 </el-checkbox-group>

 

 created() { for (let key in this.lists) { this.$set(this.checkList, key, []) } }
相關文章
相關標籤/搜索