ant design作为一套企业级UI框架,从诞生至今经历多次迭代,有react、vue、angular三种主流框架的版本,在组件封装方面已经很全面了,几乎涵盖了前端所有的UI场景,前端top也在不断提升,但仍然存在一些不足。
近期,在用antdesign做项目时用到了树形表格,要求树表格可以级联选择,满心欢喜的去照搬官方文档,╯^oo╰我擦^oo,
有点小失望,~~~~难道是vue版的不支持?赶紧去查一些react版,发现还是一样,哎,心有点凉。不过没关系,想我纵横前端这么多年,这点小功能还是难不倒我的,于是乎·····
- 先写模板,注意:
rowSelection
<template>
<a-table :rowSelection="rowSelection" :columns="columns" :dataSource="data" />
</template>
- 照搬官方api
rowSelection #
选择功能的配置。
data() {
return {
selectedRowKeys:[]
}
},
computed: {
rowSelection() {
const { selectedRowKeys } = this;
return {
selectedRowKeys,
onChange: this.onSelectChange,
hideDefaultSelections: true,
onSelect: this.onSelect,//触发级联的方法
};
}
},
- 别眨眼,级联方法已就位,处理层级数据,理所当然想到了递归
methods: {
onSelectChange(selectedRowKeys) {
console.log('selectedRowKeys changed: ', selectedRowKeys);
this.selectedRowKeys = selectedRowKeys;
},
onSelect(record, selected){//每个复选框点击都会触发
const selectrows=[record.key];
if(record.hasOwnProperty('children')){
const generator = (record) => {
//这里做一个递归查找
record.forEach(item => {
selectrows.push(item.key)
if (item.children && item.children.length > 0) {
generator(item.children,)
}
})
}
generator(record.children)
}
const newselect=this.selectedRowKeys.filter(item=>!selectrows.includes(item))
//选中和取消选中的级联
selected ? (this.selectedRowKeys = [...this.selectedRowKeys,...selectrows]):(this.selectedRowKeys = newselect)
}
}
至此树表格级联选择的功能已完成,关键代码就是onSelect
,so Easy
完整示例
<template>
<a-table :rowSelection="rowSelection" :columns="columns" :dataSource="data" />
</template>
<script>
export default {
data() {
return {
selectedRowKeys:[]
}
},
computed: {
rowSelection() {
const { selectedRowKeys } = this;
return {
selectedRowKeys,
onChange: this.onSelectChange,
hideDefaultSelections: true,
onSelect: this.onSelect,
};
}
},
methods: {
onSelectChange(selectedRowKeys) {
console.log('selectedRowKeys changed: ', selectedRowKeys);
this.selectedRowKeys = selectedRowKeys;
},
onSelect(record, selected){//每个复选框点击都会触发
const selectrows=[record.key];
if(record.hasOwnProperty('children')){
const generator = (record) => {
record.forEach(item => {
selectrows.push(item.key)
if (item.children && item.children.length > 0) {
generator(item.children,)
}
})
}
generator(record.children)
}
const newselect=this.selectedRowKeys.filter(item=>!selectrows.includes(item))
selected ? (this.selectedRowKeys = [...this.selectedRowKeys,...selectrows]):(this.selectedRowKeys = newselect)
}
}
};
</script>