Element el-checkbox-group v-model不支持对象(object)解决方案
作者:ZionHH
本文主要介绍了Element el-checkbox-group v-model不支持对象(object)解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
这个问题在官方 Issues 看到不少相关问题 [Feature Request] checkbox-group value bound object array
但是官方没有计划支持
方法一 (推荐)

label 还是绑定官方限定的类型,在选中后使用 computed 实现

<template>
<div id="app">
<el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
<div style="margin: 15px 0;"></div>
<el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
<el-checkbox v-for="city in cities" :label="city.id" :key="city.id">{{city.name}}</el-checkbox>
</el-checkbox-group>
</div>
</template>
<script>
export default {
name: 'Demo',
components: {
},
data () {
return {
checkAll: false,
checkedCities: [],
cities: [
{ id: 1, name: '北京' },
{ id: 2, name: '上海' },
{ id: 3, name: '广州' },
{ id: 4, name: '深圳' },
{ id: 5, name: '杭州' }
],
isIndeterminate: true
}
},
computed: {
// 选中的对象数组
checkedObj () {
return this.cities.filter(
option => this.checkedCities.some(
checked => checked === option.id
)
)
}
},
watch: {
checkedObj: {
handler (val) {
console.log(val)
},
deep: true,
immediate: true
}
},
methods: {
// 全选
handleCheckAllChange(val) {
this.checkedCities = val ? this.cities.map(item => item.id) : []
this.isIndeterminate = false
},
// 选择
handleCheckedCitiesChange(value) {
let checkedCount = value.length
this.checkAll = checkedCount === this.cities.length
this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length
}
}
}
</script>方法二
https://www.jb51.net/javascript/285193umm.htm(原博客地址)
注意: 在你的项目中修改无效!
1、把 element 源码克隆到本地
git clone https://github.com/ElemeFE/element.git
或者下 zip 包 https://github.com/ElemeFE/element
2、npm install
3、找到目录(packages\checkbox\src)中的 checkbox-button.vue 和 checkbox.vue 文件

将图中红框中的代码替换为以下代码
return this.model.indexOf(this.label) > -1 || JSON.stringify(this.model).indexOf(JSON.stringify(this.label)) > -1
npm run dist,将生成的 lib 文件夹替换你的项目里 node-module 的 element-ui 文件夹中的 lib 文件夹
这样就可以直接绑定 object 了
到此这篇关于Element el-checkbox-group v-model不支持对象(object)解决方案的文章就介绍到这了,更多相关el-checkbox-group v-model object内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
