需求
選中父節(jié)點(diǎn)歼秽,子節(jié)點(diǎn)默認(rèn)全選,取消一個(gè)子節(jié)點(diǎn)看疗,那么這個(gè)子節(jié)點(diǎn)的所有父節(jié)點(diǎn)都取消掉選中狀態(tài),但是其兄弟節(jié)點(diǎn)不會(huì)受影響睦授。
場(chǎng)景
場(chǎng)景一: 點(diǎn)擊‘你好’两芳,所有子節(jié)點(diǎn)全選中
場(chǎng)景二: 點(diǎn)擊‘再見(jiàn)’,取消‘再見(jiàn)’和‘你好’節(jié)點(diǎn)
場(chǎng)景三:點(diǎn)擊‘3’去枷,最下層節(jié)點(diǎn)‘4’也會(huì)被選中怖辆。取消最下層節(jié)點(diǎn)‘4’,節(jié)點(diǎn)‘3’也會(huì)被取消
代碼
以下為完整代碼:
<template>
<div class="custom-tree-container">
<div class="block">
<p>使用 scoped slot</p>
<el-tree
:data="treeList"
ref="tree"
@check="clickDeal"
:check-strictly="true"
show-checkbox
node-key="id"
default-expand-all
:expand-on-click-node="false"
@check-change="checkChange"
:props="leftProps"
>
<span class="custom-tree-node" slot-scope="{ node, data }">
<span>{{ node.label }}</span>
</span>
</el-tree>
</div>
</div>
</template>
<script>
export default {
props: {
treeList: {
type: Array,
default() {
return []
}
}
},
name: 'treeTest',
components: {},
data() {
return {
leftProps: {
label: 'name'
},
isClickSelected: false
}
},
methods: {
checkChange(obj, isChecked, isChildChecked) {
// 取消删顶,子節(jié)點(diǎn)只要有一個(gè)被取消父節(jié)點(diǎn)就被取消
if (!isChecked) {
this.$refs.tree.setChecked(obj.p_id, false)
}
},
clickDeal(currentObj, treeStatus) {
// 用于:父子節(jié)點(diǎn)嚴(yán)格互不關(guān)聯(lián)時(shí)竖螃,父節(jié)點(diǎn)勾選變化時(shí)通知子節(jié)點(diǎn)同步變化,實(shí)現(xiàn)單向關(guān)聯(lián)逗余。
let selected = treeStatus.checkedKeys.indexOf(currentObj.id) // -1未選中
this.isClickSelected = selected
// 選中
if (selected !== -1) {
// 子節(jié)點(diǎn)只要被選中父節(jié)點(diǎn)就被選中
this.selectedChildren(currentObj)
// 統(tǒng)一處理子節(jié)點(diǎn)為相同的勾選狀態(tài)
this.uniteChildSame(currentObj, true)
} else {
// 未選中 處理子節(jié)點(diǎn)全部未選中
if (currentObj.children && currentObj.children.length !== 0) {
this.uniteChildSame(currentObj, false)
}
}
},
// 統(tǒng)一處理子節(jié)點(diǎn)為相同的勾選狀態(tài)
uniteChildSame(treeList, isSelected) {
this.$refs.tree.setChecked(treeList.id, isSelected)
let childLen = treeList.children ? treeList.children.length : 0
if (childLen) {
for (let i = 0; i < childLen; i++) {
this.uniteChildSame(treeList.children[i], isSelected)
}
}
},
// 統(tǒng)一處理子節(jié)點(diǎn)為選中
selectedChildren(currentObj) {
let currentNode = this.$refs.tree.getNode(currentObj)
currentNode.childNodes.map(item => {
if (item.key !== undefined) {
this.$refs.tree.setChecked(item, true)
this.selectedChildren(item)
}
})
}
}
}
</script>
<style lang="scss" scoped>
</style>
數(shù)據(jù)結(jié)構(gòu)
這是后端返回的數(shù)據(jù)的結(jié)構(gòu):