问题:element UI el-tree 选择状态回显时,需要默认选中数据,这时调用this.$refs.tree.setCheckedKeys(array),发现array选中数据里只要包含父级id,那么它下面的所有子级都会被选中,但实际上我们并不没有选中所有子级,而是只选中其中一个或者两个,以及父级呈现半选中状态,这才是我们要的效果。
代码如下:
// 初始化菜单数据
async onLoad() {
this.loading = true
const response = await getList(this.paramsMenu)
const { data } = response
// 转为树形数据结构
this.treeData = this.filter(data)
// 找出所有父节点id
const parentIds = this.treeData.map(item => item.id)
// 从获取的已选择的数据中过滤掉父节点id,从而得到所有子节点id
const childrenIds = this.defaultChecked.filter(id => !parentIds.includes(id))
// 选中子节点,这时候父节点的选中状态就会成为合理的选择状态,即: 选中所有子节点-父节点呈现选中状态 不选中所有子节点-父节点会呈现半选中状态
this.$refs.tree.setCheckedKeys(childrenIds)
this.loading = false
},
// 处理选中数据
getCheckedNodes() {
// 获取所有状态的父节点key
let parentList = this.$refs.tree.getHalfCheckedKeys()
// 获取选中状态的子节点key
let chirenldList = this.$refs.tree.getCheckedKeys()
// 合并返回: 保存时提交的数据
return [...parentList,...chirenldList]
},
效果图: