iview 折叠面板 Collapse 和 多选框 Checkbox 搭配 for 循环使用

需求场景:折叠面板中有数据项,数据项有多选和全选以及取消全选的功能,折叠面板通过数组 for 循环生成并渲染,Checkbox 与 CheckboxGroup 也是通过数组中的数据 for 循环以及绑定

遇到的问题:代码按照逻辑写完之后,CheckboxGroup 不能按照正常情况工作,全选和取消全选错乱

解决办法:全选时不要将 checkAllGroup 直接带入运算,创建一个过渡变量,代入遍历赋值运算,最后将运算的值赋值给 checkAllGroup


      
        
        全选

        
  • {{ item.name }}
export default {
  data () {
    return {
      fruitDatas: [
        {
          isCheck: false,
          isIndeterminate: true,
          datas: [
            {
              id: 1,
              name: '香蕉'
            },
            {
              id: 2,
              name: '苹果'
            },
            {
              id: 3,
              name: '西瓜'
            }
          ]
        },
        {
          isCheck: false,
          isIndeterminate: true,
          datas: [
            {
              id: 4,
              name: '葡萄'
            },
            {
              id: 5,
              name: '橘子'
            },
            {
              id: 6,
              name: '哈密瓜'
            }
          ]
        },
        {
          isCheck: false,
          isIndeterminate: true,
          datas: [
            {
              id: 7,
              name: '圣女果'
            },
            {
              id: 8,
              name: '草莓'
            },
            {
              id: 9,
              name: '柠檬'
            }
          ]
        }
      ],
      currentIndex: null,
      fruitCheckAllGroup: [[], [], []]
    }
  },
  methods: {
    handleFruitCheckAll (isIndeterminate, currentIndex) {
      this.currentIndex = currentIndex
      this.fruitDatas.map((fruit, index) => {
        if (index === currentIndex) {
          if (isIndeterminate) {
            fruit.isCheck = false
          } else {
            fruit.isCheck = !fruit.isCheck
          }

          fruit.isIndeterminate = false

          if (fruit.isCheck) {
            // 若直接将 fruitCheckAllGroup 代入运算则全选和取消全选会出现错乱
            let checkFrunts = []
            fruit.datas.map(item => {
              checkFrunts.push(item.id)
            })

            this.fruitCheckAllGroup[index] = checkFrunts
          } else {
            this.fruitCheckAllGroup[index] = []
          }
        }
      })
    },
    fruitCheckAllGroupChange (data) {
      this.fruitDatas.map((frunt, index) => {
        if (index === this.currentIndex) {
          if (data.length === frunt.datas.length) {
            frunt.isIndeterminate = false
            frunt.isCheck = true
          } else if (data.length > 0) {
            frunt.isIndeterminate = true
            frunt.isCheck = false
          } else {
            frunt.isIndeterminate = false
            frunt.isCheck = false
          }
        }
      })
    }
  }
}
.ivu-checkbox + span,
.ivu-checkbox-wrapper + span {
  display: none;
}

最终效果:

iview 折叠面板 Collapse 和 多选框 Checkbox 搭配 for 循环使用_第1张图片

你可能感兴趣的:(vue,前端,iview)