在用element ui Checkbox 多选框组件时,业务需求需要使label的类型为Object,使用时发现label无法回显,查询资料才发现element ui Checkbox 多选框组件 lable不支持Object类型的值的问题。
后查资料发现element ui的开发人员知道这个问题,但是回复,在正式版本不打算修改,但给出了解决方法,写了一个新的组件。
<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>
使用该组件就可以支持OBJECT 类型了。
使用方法:
引入上面新的组件,然后按照下方使用方法就能支持OBJECT 类型了。
<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>