@@ -163,6 +163,22 @@ export default {
163163 }
164164 return null
165165 },
166+ /**
167+ * 搜寻n叉树节点路径
168+ * @param { Object } targetNode 目标节点
169+ * @param { Array } data 将要搜寻的树结构, 默认为根节点
170+ * @return { Array } 返回从根节点到目标节点之间的所有节点
171+ */
172+ _getRootPath (node , data = this .deepData ) {
173+ const { children } = this .defaultProps
174+ for (let i = 0 ; i < data .length ; i++ ) {
175+ const item = data[i]
176+ if (item === node) return [item]
177+ const nodePath = this ._getRootPath (node, item[children])
178+ if (nodePath .length ) return [item, ... nodePath]
179+ }
180+ return []
181+ },
166182 _initNode (node , parent ) { // 初始化节点
167183 const { name , children , disabled } = this .defaultProps
168184 const key = node[this .nodeKey ]
@@ -223,7 +239,7 @@ export default {
223239 })
224240 return getSortData (tree)
225241 },
226- _downwardUpdateChecked (data , checked ) { // 向下处理树节点的checked
242+ _updateChecked (data , checked ) { // 更新当前节点的状态
227243 const { children , disabled } = this .defaultProps
228244 // 如果当前节点是叶子节点, 只需要判断disabled即可
229245 if (! data[children].length ) return ! data[disabled] && (data .checked = checked)
@@ -248,7 +264,10 @@ export default {
248264 data .checked = checked
249265 // 由于两种状态可能叠加存在, 所以oneNodeIsDisabledAndUncheck的判断放在后面
250266 if (oneNodeIsDisabledAndUncheck) data .checked = false
251- // 可以向下继续遍历
267+ },
268+ _downwardUpdateChecked (data , checked ) { // 向下处理树节点的checked
269+ const { children } = this .defaultProps
270+ this ._updateChecked (data, checked)
252271 data[children].forEach (item => this ._downwardUpdateChecked (item, checked))
253272 },
254273 getNodeByKey (key ) { // 根据key获取对应深拷贝节点
@@ -258,18 +277,29 @@ export default {
258277 return this ._preorder (this .deepData , item => item[this .nodeKey ] == key)
259278 },
260279 resetChecked () { // 取消所有节点的选中状态
261- return ! this ._preorder ( this . deepData , item => (item . checked = false , item . indeterminate = false ))
280+ this .deepData . forEach ( item => this . _downwardUpdateChecked (item, false ))
262281 },
263282 setCheckedByKeys (keys , checked ) { // 设置指定keys节点的checked
264283 if (! keys .length ) return null
265284 keys = deepCopy (keys)
285+ const nodes = []
286+ // 向下处理节点的选中状态, 并记录nodes
266287 this ._preorder (this .deepData , item => {
267288 let index = keys .indexOf (item[this .nodeKey ])
268289 if (index === - 1 ) return false
269290 this ._downwardUpdateChecked (item, checked)
291+ nodes .push (item)
270292 keys .splice (index, 1 )
271293 return ! keys .length
272294 })
295+ // 对公共祖先节点进行合并和去重操作
296+ let ancestorNodes = []
297+ nodes .forEach (item => {
298+ let nodePath = this ._getRootPath (item)
299+ nodePath .pop ()
300+ ancestorNodes = [... new Set ([... ancestorNodes, ... nodePath])]
301+ })
302+ ancestorNodes .forEach (item => this ._updateChecked (item, checked))
273303 },
274304 getCheckedKeys (nodeKey = this .nodeKey ) { // 获取所有选中节点的keys
275305 const keys = []
0 commit comments