element ui Checkbox 多选框组件 lable不支持Object类型的值的问题

浅浅记录一下,遇到这个问题的心理路程吧,首先我遇到的问题是多选框的值回显不打对勾,(例如:你新增的时候多选,然后点击编辑的时候选过的值没有被勾选,其实是被勾选上了,但是没有显示对勾,因为我点击已经选择过值就会取消勾选,说明这个值其实是回显了,但是不显示对勾),然后我就去查element ui,发现他的多选框的label只支持string / number / boolean,不支持object的形式,但是我的业务场景需要label的类型为object,于是尝试了各种方法之后,找到了一个最为合适的解决方案

 1.写一个新组件


<script>
// new-el-checkbox.vue 支持OBJECT 类型
import { defineComponent } from '@vue/composition-api'
import { Checkbox } from 'element-ui'
import _isEqual from 'lodash/isEqual'

// Now support array of object by adding _isEqual to compare the values
// Specify the value of checkbox with 'label' prop, not 'value' prop
export default defineComponent({
  extends: Checkbox,
  computed: {
    // eslint-disable-next-line vue/return-in-computed-property
    isChecked() {
      if ({}.toString.call(this.model) === '[object Boolean]') {
        return this.model
      } else if (Array.isArray(this.model)) {
        return this.model.find((item) => _isEqual(item, this.label))
      } else if (this.model !== null && this.model !== undefined) {
        return this.model === this.trueLabel
      }
    },
  },
  methods: {
    addToStore() {
      if (Array.isArray(this.model)) {
        const isExisted = this.model.find((item) => _isEqual(item, this.label))
        if (!isExisted) this.model.push(this.label)
      } else {
        this.model = this.trueLabel || true
      }
    },
  },
})
</script>

2.在你的多选框页面引用上面的组件,然后将下面的方法进行改写你的多选框组件

<el-checkbox-group v-model="value" >
    <new-el-checkbox  v-for="item in Options" :label="item" :key="item.id">{{ item.label  }}
    </new-el-checkbox>
</el-checkbox-group>

<script>
import newElCheckbox "@/components/newCheckbox.vue";
export default{
    components:{
    newElCheckboxfrom
  },
}
</script>

  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

阿wei程序媛

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

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

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

打赏作者

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

抵扣说明:

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

余额充值