问题描述
如果数据的子节点命名时children,就没有任何问题,如果后端数据结构子节点是其他名字,比如thisChildList
就有bug
const tableData = [{id: 1,date: '2016-05-02',name: 'wangxiaohu',address: 'No. 189, Grove St, Los Angeles',selectedAble: true,thisChildList: [{id: 131,date: '2016-05-01',name: 'wangxiaohu',address: 'No. 189, Grove St, Los Angeles',selectedAble: true,thisChildList: [...]},]
解决
参考大佬的代码
传送门
// 递归const setChildren = (children, type) => {// 编辑多个子层级children.map((j) => {toggleSelection(j, type)if (j.thisChildList) {setChildren(j.thisChildList, type)}})}// 选中父节点时,子节点一起选中取消const select = (selection, row) => {console.log('select!!')const hasSelect = selection.some((el) => {return row.id === el.id})console.log('hasSelect', hasSelect)if (hasSelect) {if (row.thisChildList) {// 解决子组件没有被勾选到setChildren(row.thisChildList, true)}} else {// 解决点击父组件取消选中,子级也跟着取消if (row.thisChildList) {setChildren(row.thisChildList, false)}}}const toggleSelection = (row, select) => {if (row) {// 通过使用 nextTick 来延迟执行后续的代码,以确保在更新表格的选中状态之前先进行其他可能的 DOM 更新nextTick(() => {// 这里 && 的作用是 如果左侧表达式的值为真值,则返回右侧表达式的值;// 否则,返回左侧表达式的值。如果左侧表达式的值为假值,则整个表达式的结果也为假值。// toggleRowSelection用于多选表格,切换某一行的选中状态, 如果使用了第二个参数,则可直接设置这一行选中与否multipleTable.value && multipleTable.value.toggleRowSelection(row, select)// 也可以写成 multipleTable.value?.toggleRowSelection(row, select)})}}// 选择全部 默认全选框只能影响第一级的 二、三等级别不会联动// 当用户手动勾选全选 Checkbox 时触发的事件const selectAll = (selection) => {console.log('selectAll——————selection', selection)// tabledata第一层只要有在selection里面就是全选const isSelect = selection.some((el) => {const tableDataIds = tableData.map((j) => j.id)return tableDataIds.includes(el.id)})// tableDate第一层只要有不在selection里面就是全不选const isCancel = !tableData.every((el) => {const selectIds = selection.map((j) => j.id)return selectIds.includes(el.id)})if (isSelect) {selection.map((el) => {if (el.thisChildList) {// 解决子组件没有被勾选到setChildren(el.thisChildList, true)}})}if (isCancel) {tableData.map((el) => {if (el.thisChildList) {// 解决子组件没有被勾选到setChildren(el.thisChildList, false)}})}}// const selectionChange = (val) => {// console.log(val)// }
但仍然有问题,比如3级节点选中,他的父级节点无动于衷,不会联动
解决2
或者把thisChildList 改成children
function renameChildListToChildren(data) {if (!Array.isArray(data)) {return data;}return data.map(item => {const newItem = { ...item };if (newItem.thisChildList) {newItem.children = renameChildListToChildren(newItem.thisChildList);delete newItem.thisChildList;}return newItem;});
}const newData = renameChildListToChildren(tableData);
console.log(newData);
但是官方也有这个问题
二级不能影响一级的选中,有bug