From 5241c3bfc312d92f2ae71705adf9ecd4244d716b Mon Sep 17 00:00:00 2001 From: ChuChencheng Date: Wed, 31 Jul 2024 04:07:55 +0800 Subject: [PATCH 1/4] feat: add update node APIs --- src/components/Tree.vue | 4 +++ src/constants/index.ts | 2 ++ src/hooks/usePublicTreeAPI.ts | 14 ++++++++++ src/store/tree-store.ts | 52 +++++++++++++++++++++++++++++++++++ 4 files changed, 72 insertions(+) diff --git a/src/components/Tree.vue b/src/components/Tree.vue index e8ab382..4f70e63 100644 --- a/src/components/Tree.vue +++ b/src/components/Tree.vue @@ -405,6 +405,8 @@ const { filter, showCheckedNodes, loadRootNodes, + updateNode, + updateNodes, } = usePublicTreeAPI(nonReactive, props, { resetSpaceHeights, updateExpandedKeys, @@ -705,6 +707,8 @@ defineExpose({ filter, showCheckedNodes, loadRootNodes, + updateNode, + updateNodes, scrollTo, }) diff --git a/src/constants/index.ts b/src/constants/index.ts index b316bdf..6a5ae03 100644 --- a/src/constants/index.ts +++ b/src/constants/index.ts @@ -39,6 +39,8 @@ export const TREE_API_METHODS = [ 'filter', 'showCheckedNodes', 'loadRootNodes', + 'updateNode', + 'updateNodes', 'scrollTo' ] as const diff --git a/src/hooks/usePublicTreeAPI.ts b/src/hooks/usePublicTreeAPI.ts index 7c553a2..d22737f 100644 --- a/src/hooks/usePublicTreeAPI.ts +++ b/src/hooks/usePublicTreeAPI.ts @@ -235,6 +235,18 @@ export const usePublicTreeAPI = ( isRootLoading.value = false }) } + /** + * 更新单个节点 + */ + function updateNode(key: TreeNodeKeyType, newNode: ITreeNodeOptions) { + return nonReactive.store.updateNode(key, newNode) + } + /** + * 更新多个节点 + */ + function updateNodes(newNodes: ITreeNodeOptions[]) { + return nonReactive.store.updateNodes(newNodes) + } return { unloadCheckedNodes, @@ -269,5 +281,7 @@ export const usePublicTreeAPI = ( filter, showCheckedNodes, loadRootNodes, + updateNode, + updateNodes, } } diff --git a/src/store/tree-store.ts b/src/store/tree-store.ts index 79e5d60..68068cb 100644 --- a/src/store/tree-store.ts +++ b/src/store/tree-store.ts @@ -518,6 +518,58 @@ export default class TreeStore extends TreeEventTarget { } } + updateNode(key: TreeNodeKeyType, newNode: ITreeNodeOptions, triggerDataChange = true) { + if (!this.mapData[key]) return + + const newNodeCopy: ITreeNodeOptions = {} + const notAllowedFields = [ + this.options.keyField, + 'indeterminate', + 'visible', + 'isLeaf', + ] + + // Exclude key field and fields starting with '_' + Object.keys(newNode).forEach((field) => { + if (!field.startsWith('_') && !notAllowedFields.includes(field)) { + newNodeCopy[field] = newNode[field] + } + }) + + if (Array.isArray(newNodeCopy.children)) { + this.mapData[key].setChildren(newNodeCopy.children) + delete newNodeCopy.children + } + if ('checked' in newNodeCopy) { + this.setChecked(key, newNodeCopy.checked, false, false) + delete newNodeCopy.checked + } + if ('selected' in newNodeCopy) { + this.setSelected(key, newNodeCopy.selected, false, false) + delete newNodeCopy.selected + } + if ('expand' in newNodeCopy) { + this.setExpand(key, newNodeCopy.expand, false, false, false) + delete newNodeCopy.expand + } + Object.keys(newNodeCopy).forEach((field) => { + this.mapData[key][field] = newNodeCopy[field] + }) + + if (triggerDataChange) { + this.emit('visible-data-change') + } + } + + updateNodes(newNodes: ITreeNodeOptions[]) { + const validNodes = newNodes.filter((node) => node[this.options.keyField] != null) + validNodes.forEach((node) => { + this.updateNode(node[this.options.keyField], node, false) + }) + + this.emit('visible-data-change') + } + //#endregion Set api //#region Get api From a3e662c5685df9717d7b6aa570f649753c34a0f5 Mon Sep 17 00:00:00 2001 From: ChuChencheng Date: Thu, 1 Aug 2024 02:36:44 +0800 Subject: [PATCH 2/4] feat: update children --- site/.vitepress/code/ReloadChildren.vue | 60 +++++++ site/.vitepress/code/UpdateNodeTitle.vue | 73 +++++++++ site/examples/node-manipulation.md | 14 ++ src/store/tree-store.ts | 191 +++++++++++++++-------- 4 files changed, 276 insertions(+), 62 deletions(-) create mode 100644 site/.vitepress/code/ReloadChildren.vue create mode 100644 site/.vitepress/code/UpdateNodeTitle.vue diff --git a/site/.vitepress/code/ReloadChildren.vue b/site/.vitepress/code/ReloadChildren.vue new file mode 100644 index 0000000..47b2908 --- /dev/null +++ b/site/.vitepress/code/ReloadChildren.vue @@ -0,0 +1,60 @@ + + + + + diff --git a/site/.vitepress/code/UpdateNodeTitle.vue b/site/.vitepress/code/UpdateNodeTitle.vue new file mode 100644 index 0000000..9eb4e82 --- /dev/null +++ b/site/.vitepress/code/UpdateNodeTitle.vue @@ -0,0 +1,73 @@ + + + + + diff --git a/site/examples/node-manipulation.md b/site/examples/node-manipulation.md index 36a1e41..a07ed86 100644 --- a/site/examples/node-manipulation.md +++ b/site/examples/node-manipulation.md @@ -22,3 +22,17 @@ - 调用树组件的 `remove` 方法,可移除节点 + +## 更新节点名称 {#update-node-title} + +调用树组件的 `updateNode` 方法可更新节点部分字段 + +调用 `updateNodes` 可批量更新 + + + +## 重新加载子节点 {#reload-children} + +调用 `updateNode` 传入新的 `children` 列表可以重新加载子节点 + + diff --git a/src/store/tree-store.ts b/src/store/tree-store.ts index 68068cb..6a4774f 100644 --- a/src/store/tree-store.ts +++ b/src/store/tree-store.ts @@ -232,8 +232,8 @@ export default class TreeStore extends TreeEventTarget { * @param triggerDataChange 是否触发视图刷新 */ private triggerCheckedChange( - triggerEvent: boolean = true, - triggerDataChange: boolean = true + triggerEvent = true, + triggerDataChange = true, ) { if (triggerEvent) { this.emit('checked-change', this.getCheckedNodes(), this.getCheckedKeys()) @@ -244,6 +244,24 @@ export default class TreeStore extends TreeEventTarget { } } + /** + * 触发 selected-change 的快捷方法 + * @param triggerEvent 是否触发事件 + * @param triggerDataChange 是否触发视图刷新 + */ + private triggerSelectedChange( + triggerEvent = true, + triggerDataChange = true, + ) { + if (triggerEvent) { + this.emit('selected-change', this.getSelectedNode(), this.getSelectedKey()) + } + + if (triggerDataChange) { + this.emit('render-data-change') + } + } + /** * 设置单选选中 * @param key 选中节点 key @@ -294,17 +312,9 @@ export default class TreeStore extends TreeEventTarget { } else { this.emit('unselect', node) } - - this.emit( - 'selected-change', - this.getSelectedNode(), - this.getSelectedKey() - ) } - if (triggerDataChange) { - this.emit('render-data-change') - } + this.triggerSelectedChange(triggerEvent, triggerDataChange) } /** @@ -327,17 +337,7 @@ export default class TreeStore extends TreeEventTarget { } } - if (triggerEvent) { - this.emit( - 'selected-change', - this.getSelectedNode(), - this.getSelectedKey() - ) - } - - if (triggerDataChange) { - this.emit('render-data-change') - } + this.triggerSelectedChange(triggerEvent, triggerDataChange) } /** @@ -359,17 +359,7 @@ export default class TreeStore extends TreeEventTarget { } else if (this.unloadSelectedKey !== null) { this.unloadSelectedKey = null - if (triggerEvent) { - this.emit( - 'selected-change', - this.getSelectedNode(), - this.getSelectedKey() - ) - } - - if (triggerDataChange) { - this.emit('render-data-change') - } + this.triggerSelectedChange(triggerEvent, triggerDataChange) } } @@ -518,7 +508,7 @@ export default class TreeStore extends TreeEventTarget { } } - updateNode(key: TreeNodeKeyType, newNode: ITreeNodeOptions, triggerDataChange = true) { + updateNode(key: TreeNodeKeyType, newNode: ITreeNodeOptions, triggerEvent = true, triggerDataChange = true) { if (!this.mapData[key]) return const newNodeCopy: ITreeNodeOptions = {} @@ -536,8 +526,25 @@ export default class TreeStore extends TreeEventTarget { } }) - if (Array.isArray(newNodeCopy.children)) { - this.mapData[key].setChildren(newNodeCopy.children) + const previousCheckedKeys = this.getCheckedKeys() + const previousSelectedKey = this.getSelectedKey() + + if ('children' in newNodeCopy) { + // remove all children + const childKeys = this.mapData[key].children.map((child) => child[this.options.keyField]) + childKeys.forEach((childKey) => { + // TODO: 重新写一个批量移除 children 的函数 + this.remove(childKey, false, false) + }) + + // add new children + if (Array.isArray(newNodeCopy.children)) { + newNodeCopy.children.forEach((child) => { + // TODO: 批量添加抽离 setExpand 中 load children 的逻辑 + this.append(child, key, false, false) + }) + } + delete newNodeCopy.children } if ('checked' in newNodeCopy) { @@ -556,6 +563,19 @@ export default class TreeStore extends TreeEventTarget { this.mapData[key][field] = newNodeCopy[field] }) + const currentCheckedKeys = this.getCheckedKeys() + const currentSelectedKey = this.getSelectedKey() + + if (triggerEvent) { + if (JSON.stringify(currentCheckedKeys.sort()) !== JSON.stringify(previousCheckedKeys.sort())) { + this.triggerCheckedChange(true, false) + } + + if (currentSelectedKey !== previousSelectedKey) { + this.triggerSelectedChange(true, false) + } + } + if (triggerDataChange) { this.emit('visible-data-change') } @@ -563,10 +583,26 @@ export default class TreeStore extends TreeEventTarget { updateNodes(newNodes: ITreeNodeOptions[]) { const validNodes = newNodes.filter((node) => node[this.options.keyField] != null) + if (!validNodes.length) return + + const previousCheckedKeys = this.getCheckedKeys() + const previousSelectedKey = this.getSelectedKey() + validNodes.forEach((node) => { - this.updateNode(node[this.options.keyField], node, false) + this.updateNode(node[this.options.keyField], node, false, false) }) + const currentCheckedKeys = this.getCheckedKeys() + const currentSelectedKey = this.getSelectedKey() + + if (JSON.stringify(currentCheckedKeys.sort()) !== JSON.stringify(previousCheckedKeys.sort())) { + this.triggerCheckedChange(true, false) + } + + if (currentSelectedKey !== previousSelectedKey) { + this.triggerSelectedChange(true, false) + } + this.emit('visible-data-change') } @@ -670,12 +706,14 @@ export default class TreeStore extends TreeEventTarget { insertBefore( insertedNode: TreeNodeKeyType | ITreeNodeOptions, - referenceKey: TreeNodeKeyType + referenceKey: TreeNodeKeyType, + triggerEvent = true, + triggerDataChange = true, ): TreeNode | null { const node = this.getInsertedNode(insertedNode, referenceKey) if (!node) return null - this.remove(node[this.options.keyField], false) + this.remove(node[this.options.keyField], false, false) const referenceNode = this.mapData[referenceKey] const parentNode = referenceNode._parent @@ -688,19 +726,25 @@ export default class TreeStore extends TreeEventTarget { const dataIndex = (parentNode && -1) || this.findIndex(referenceKey, this.data) - this.insertIntoStore(node, parentNode, childIndex, flatIndex, dataIndex) - this.emit('visible-data-change') + this.insertIntoStore(node, parentNode, childIndex, flatIndex, dataIndex, triggerEvent, triggerDataChange) + + if (triggerDataChange) { + this.emit('visible-data-change') + } + return node } insertAfter( insertedNode: TreeNodeKeyType | ITreeNodeOptions, - referenceKey: TreeNodeKeyType + referenceKey: TreeNodeKeyType, + triggerEvent = true, + triggerDataChange = true, ): TreeNode | null { const node = this.getInsertedNode(insertedNode, referenceKey) if (!node) return null - this.remove(node[this.options.keyField], false) + this.remove(node[this.options.keyField], false, false) const referenceNode = this.mapData[referenceKey] const parentNode = referenceNode._parent @@ -726,57 +770,77 @@ export default class TreeStore extends TreeEventTarget { const dataIndex = (parentNode && -1) || this.findIndex(referenceKey, this.data) + 1 - this.insertIntoStore(node, parentNode, childIndex, flatIndex, dataIndex) - this.emit('visible-data-change') + this.insertIntoStore(node, parentNode, childIndex, flatIndex, dataIndex, triggerEvent, triggerDataChange) + + if (triggerDataChange) { + this.emit('visible-data-change') + } + return node } append( insertedNode: TreeNodeKeyType | ITreeNodeOptions, - parentKey: TreeNodeKeyType + parentKey: TreeNodeKeyType, + triggerEvent = true, + triggerDataChange = true, ): TreeNode | null { const parentNode = this.mapData[parentKey] if (!parentNode.isLeaf) { const childrenLength = parentNode.children.length return this.insertAfter( insertedNode, - parentNode.children[childrenLength - 1][this.options.keyField] + parentNode.children[childrenLength - 1][this.options.keyField], + triggerEvent, + triggerDataChange, ) } const node = this.getInsertedNode(insertedNode, parentKey, true) if (!node) return null - this.remove(node[this.options.keyField], false) + this.remove(node[this.options.keyField], false, false) const flatIndex = this.findIndex(parentKey) + 1 - this.insertIntoStore(node, parentNode, 0, flatIndex) - this.emit('visible-data-change') + this.insertIntoStore(node, parentNode, 0, flatIndex, undefined, triggerEvent, triggerDataChange) + + if (triggerDataChange) { + this.emit('visible-data-change') + } + return node } prepend( insertedNode: TreeNodeKeyType | ITreeNodeOptions, - parentKey: TreeNodeKeyType + parentKey: TreeNodeKeyType, + triggerEvent = true, + triggerDataChange = true, ): TreeNode | null { const parentNode = this.mapData[parentKey] if (!parentNode.isLeaf) { return this.insertBefore( insertedNode, - parentNode.children[0][this.options.keyField] + parentNode.children[0][this.options.keyField], + triggerEvent, + triggerDataChange, ) } const node = this.getInsertedNode(insertedNode, parentKey, true) if (!node) return null - this.remove(node[this.options.keyField], false) + this.remove(node[this.options.keyField], false, false) const flatIndex = this.findIndex(parentKey) + 1 - this.insertIntoStore(node, parentNode, 0, flatIndex) - this.emit('visible-data-change') + this.insertIntoStore(node, parentNode, 0, flatIndex, undefined, triggerEvent, triggerDataChange) + + if (triggerDataChange) { + this.emit('visible-data-change') + } + return node } @@ -786,7 +850,8 @@ export default class TreeStore extends TreeEventTarget { */ remove( removedKey: TreeNodeKeyType, - triggerDataChange: boolean = true + triggerEvent: boolean = true, + triggerDataChange: boolean = true, ): TreeNode | null { const node = this.mapData[removedKey] if (!node) return null @@ -833,7 +898,7 @@ export default class TreeStore extends TreeEventTarget { node._parent.indeterminate = false } // 更新被移除处父节点状态 - this.updateMovingNodeStatus(node) + this.updateMovingNodeStatus(node, triggerEvent, triggerDataChange) } if (triggerDataChange) { @@ -885,7 +950,9 @@ export default class TreeStore extends TreeEventTarget { parentNode: TreeNode | null, childIndex: number, flatIndex: number, - dataIndex?: number + dataIndex?: number, + triggerEvent = true, + triggerDataChange = true, ): void { if (flatIndex === -1) return @@ -925,16 +992,16 @@ export default class TreeStore extends TreeEventTarget { this.insertIntoFlatData(flatIndex, nodes) // 更新插入节点父节点状态 - this.updateMovingNodeStatus(node) + this.updateMovingNodeStatus(node, triggerEvent, triggerDataChange) } - private updateMovingNodeStatus(movingNode: TreeNode): void { + private updateMovingNodeStatus(movingNode: TreeNode, triggerEvent = true, triggerDataChange = true): void { // 处理多选 this.checkNodeUpward(movingNode) - this.triggerCheckedChange() + this.triggerCheckedChange(triggerEvent, triggerDataChange) // 处理单选 if (movingNode.selected) { - this.setSelected(movingNode[this.options.keyField], true) + this.setSelected(movingNode[this.options.keyField], true, triggerEvent, triggerDataChange) } } From 8e51d24afafa4a246da7a19df681bf3df4c9c735 Mon Sep 17 00:00:00 2001 From: ChuChencheng Date: Fri, 9 Aug 2024 03:19:02 +0800 Subject: [PATCH 3/4] feat: extract removeChildren and loadChildren --- src/store/tree-store.ts | 89 +++++++++++++++++++++++++++++------------ 1 file changed, 63 insertions(+), 26 deletions(-) diff --git a/src/store/tree-store.ts b/src/store/tree-store.ts index 6a4774f..631615e 100644 --- a/src/store/tree-store.ts +++ b/src/store/tree-store.ts @@ -397,23 +397,7 @@ export default class TreeStore extends TreeEventTarget { }) .then(children => { if (Array.isArray(children)) { - const parentIndex: number = this.findIndex(node) - if (parentIndex === -1) return - node._loaded = true - node.expand = value - node.setChildren(children) - // 如果单选选中的值为空,则允许后续数据覆盖单选 value - const currentCheckedKeys = this.getCheckedKeys() - const flattenChildren = this.flattenData( - node.children, - this.getSelectedKey === null - ) - this.insertIntoFlatData(parentIndex + 1, flattenChildren) - // 如果有未加载的选中节点,判断其是否已加载 - this.setUnloadCheckedKeys(currentCheckedKeys) - if (this.unloadSelectedKey !== null) { - this.setUnloadSelectedKey(this.unloadSelectedKey) - } + this.loadChildren(node, children, value) this.emit('set-data') } }) @@ -531,18 +515,11 @@ export default class TreeStore extends TreeEventTarget { if ('children' in newNodeCopy) { // remove all children - const childKeys = this.mapData[key].children.map((child) => child[this.options.keyField]) - childKeys.forEach((childKey) => { - // TODO: 重新写一个批量移除 children 的函数 - this.remove(childKey, false, false) - }) + this.removeChildren(key, false, false) // add new children if (Array.isArray(newNodeCopy.children)) { - newNodeCopy.children.forEach((child) => { - // TODO: 批量添加抽离 setExpand 中 load children 的逻辑 - this.append(child, key, false, false) - }) + this.loadChildren(this.mapData[key], newNodeCopy.children, this.mapData[key].expand) } delete newNodeCopy.children @@ -908,6 +885,66 @@ export default class TreeStore extends TreeEventTarget { return node } + private removeChildren( + parentKey: TreeNodeKeyType, + triggerEvent: boolean = true, + triggerDataChange: boolean = true, + ) { + const node = this.mapData[parentKey] + if (!node || !node.children.length) return null + + const firstChild = node.children[0] + + // 从 flatData 中移除 + const index = this.findIndex(node) + if (index === -1) return null + let deleteCount = 0 + const length = this.flatData.length + for (let i = index + 1; i < length; i++) { + if (this.flatData[i]._level > node._level) { + // 从 mapData 中移除 + delete this.mapData[this.flatData[i][this.options.keyField]] + deleteCount++ + } else break + } + this.flatData.splice(index + 1, deleteCount) + + // 从父节点 children 中移除 + node.children.splice(0, node.children.length) + node.isLeaf = true + node.indeterminate = false + + // 更新被移除处父节点状态 + this.updateMovingNodeStatus(firstChild, triggerEvent, triggerDataChange) + + if (triggerDataChange) { + this.emit('visible-data-change') + } + + return node + } + + private loadChildren(node: TreeNode, children: any[], expand: boolean) { + const parentIndex: number = this.findIndex(node) + if (parentIndex === -1) return + node._loaded = true + node.expand = expand + node.setChildren(children) + node.isLeaf = !node.children.length + // 如果单选选中的值为空,则允许后续数据覆盖单选 value + const currentCheckedKeys = this.getCheckedKeys() + const flattenChildren = this.flattenData( + node.children, + this.getSelectedKey === null + ) + this.insertIntoFlatData(parentIndex + 1, flattenChildren) + // 如果有未加载的选中节点,判断其是否已加载 + this.setUnloadCheckedKeys(currentCheckedKeys) + if (this.unloadSelectedKey !== null) { + this.setUnloadSelectedKey(this.unloadSelectedKey) + } + } + private getInsertedNode( insertedNode: TreeNodeKeyType | ITreeNodeOptions, referenceKey: TreeNodeKeyType, From 77c7a2c9f183b77dbb97605fb175a0f45ffda024 Mon Sep 17 00:00:00 2001 From: ChuChencheng Date: Sun, 11 Aug 2024 02:25:01 +0800 Subject: [PATCH 4/4] feat: optimize loadChildren and update doc --- site/.vitepress/code/ReloadChildren.vue | 16 ++++- site/.vitepress/code/UpdateCustomField.vue | 66 ++++++++++++++++++++ site/api/vtree.md | 2 + site/en/api/vtree.md | 2 + site/en/examples/node-manipulation.md | 20 ++++++ site/examples/node-manipulation.md | 6 ++ src/store/tree-store.ts | 71 +++++++++++++++------- tests/unit/tree.spec.ts | 2 +- 8 files changed, 160 insertions(+), 25 deletions(-) create mode 100644 site/.vitepress/code/UpdateCustomField.vue diff --git a/site/.vitepress/code/ReloadChildren.vue b/site/.vitepress/code/ReloadChildren.vue index 47b2908..2a91d8d 100644 --- a/site/.vitepress/code/ReloadChildren.vue +++ b/site/.vitepress/code/ReloadChildren.vue @@ -1,8 +1,9 @@ @@ -47,6 +48,17 @@ const handleSetChildren = () => { const handleClearChildren = () => { tree.value.updateNode('node-1', { children: [] }) } +const handleUpdateChildren = () => { + tree.value.updateNode('node-1', { + children: children.map((child) => { + return { + ...child, + title: `${child.title} ${Date.now()}`, + checked: true, + } + }) + }) +} diff --git a/site/api/vtree.md b/site/api/vtree.md index 41d6d34..fe1aafa 100644 --- a/site/api/vtree.md +++ b/site/api/vtree.md @@ -97,6 +97,8 @@ | filter | 过滤节点 | `keyword: string`: 过滤关键词
`filterMethod: (keyword: string, node: TreeNode) => boolean`: 过滤方法,默认为 filterMethod Prop ,如果没有传 filterMethod Prop 则为搜索 title 字段的一个内置方法 | `void` | | showCheckedNodes | 展示已选节点 | `showUnloadCheckedNodes: boolean`: 是否显示未加载的选中节点,默认为 Prop 传入的值 | `void` | | loadRootNodes | 从远程加载根节点 | 无 | `Promise` | +| updateNode `4.1.0` | 更新单个节点 | `key: string \| number`: 节点 key
`newNode: object`: 新节点数据,某些字段将被忽略,例如以下划线 "_" 开头的字段,以及 key 字段和 `indeterminate`, `visible`, `isLeaf` 等 | `void` | +| updateNodes `4.1.0` | 更新多个节点 | `newNodes: object[]`: 新节点数据数组,与 `updateNode` 相同,特定的字段会被忽略,且没有 key 字段的元素将被忽略 | `void` | | scrollTo | 滚动到指定节点位置 | `key: string \| number`: 节点 key
`verticalPosition: 'top' \| 'center' \| 'bottom' \| number`: 滚动的垂直位置 | `void` | ## VTree Slots diff --git a/site/en/api/vtree.md b/site/en/api/vtree.md index ef725a0..0eb7e9b 100644 --- a/site/en/api/vtree.md +++ b/site/en/api/vtree.md @@ -97,6 +97,8 @@ Note: Since `2.0.8`, the node info returned in events contains the full node inf | filter | Filter nodes | `keyword: string`: filter keyword
`filterMethod: (keyword: string, node: TreeNode) => boolean`: filter method, default to filterMethod prop. if filterMethod prop is not present, it's an internal method that searches node title | `void` | | showCheckedNodes | Show checked nodes | `showUnloadCheckedNodes: boolean`: whether to show checked nodes that are not loaded, default to prop value | `void` | | loadRootNodes | Load root nodes from remote | None | `Promise` | +| updateNode `4.1.0` | Update single node | `key: string \| number`: node key
`newNode: object`: new node data, some fields will be ignored, like those start with underscore '_', the key field and `indeterminate`, `visible`, `isLeaf`, etc. | `void` | +| updateNodes `4.1.0` | Update multiple nodes | `newNodes: object[]`: new nodes array, some specific fields will be ignored like `updateNode`, and the elements without key field also will be ignored | `void` | | scrollTo | Scroll to specific node position | `key: string \| number`: node key
`verticalPosition: 'top' \| 'center' \| 'bottom' \| number`: vertical position of scrolling | `void` | ## VTree Slots diff --git a/site/en/examples/node-manipulation.md b/site/en/examples/node-manipulation.md index 5e4f92e..216d33c 100644 --- a/site/en/examples/node-manipulation.md +++ b/site/en/examples/node-manipulation.md @@ -22,3 +22,23 @@ Enable `draggable` and `droppable` - Invoke `remove` to remove a node + +## Update Node Title {#update-node-title} + +Invoke `updateNode` method to update some fields of tree node + +Invoke `updateNodes` to update multiple nodes + + + +## Update Custom Field {#update-custom-field} + +Invoke `updateNode` method to update custom fields in tree node + + + +## Reload Child Nodes {#reload-children} + +Invoke `updateNode` and pass a new `children` list to reload child nodes + + diff --git a/site/examples/node-manipulation.md b/site/examples/node-manipulation.md index a07ed86..98947b0 100644 --- a/site/examples/node-manipulation.md +++ b/site/examples/node-manipulation.md @@ -31,6 +31,12 @@ +## 更新自定义字段 {#update-custom-field} + +调用树组件的 `updateNode` 方法更新自定义字段 + + + ## 重新加载子节点 {#reload-children} 调用 `updateNode` 传入新的 `children` 列表可以重新加载子节点 diff --git a/src/store/tree-store.ts b/src/store/tree-store.ts index 631615e..15d1bd1 100644 --- a/src/store/tree-store.ts +++ b/src/store/tree-store.ts @@ -291,18 +291,15 @@ export default class TreeStore extends TreeEventTarget { } else { // 设置的节点不是当前已选中节点,要么当前没有选中节点,要么当前有选中节点 if (value) { - if (this.currentSelectedKey === null) { - // 当前没有选中节点 - node.selected = value - this.currentSelectedKey = node[this.options.keyField] - } else { + if (this.currentSelectedKey !== null) { // 取消当前已选中,设置新的选中节点 if (this.mapData[this.currentSelectedKey]) { this.mapData[this.currentSelectedKey].selected = false } - node.selected = value - this.currentSelectedKey = node[this.options.keyField] } + node.selected = value + this.currentSelectedKey = node[this.options.keyField] + this.unloadSelectedKey = null } } @@ -327,9 +324,7 @@ export default class TreeStore extends TreeEventTarget { triggerDataChange: boolean = true ): void { if (value) { - if (this.currentSelectedKey) { - this.setSelected(this.currentSelectedKey, false, false, false) - } + this.currentSelectedKey = null this.unloadSelectedKey = key } else { if (this.unloadSelectedKey === key) { @@ -492,8 +487,13 @@ export default class TreeStore extends TreeEventTarget { } } + private isChildrenChanged(node: TreeNode, newNode: ITreeNodeOptions): boolean { + return ('children' in newNode) && (!!node.children.length || !!newNode.children?.length) + } + updateNode(key: TreeNodeKeyType, newNode: ITreeNodeOptions, triggerEvent = true, triggerDataChange = true) { - if (!this.mapData[key]) return + const node = this.mapData[key] + if (!node) return const newNodeCopy: ITreeNodeOptions = {} const notAllowedFields = [ @@ -512,14 +512,15 @@ export default class TreeStore extends TreeEventTarget { const previousCheckedKeys = this.getCheckedKeys() const previousSelectedKey = this.getSelectedKey() + let triggerSetDataFlag = this.isChildrenChanged(node, newNodeCopy) - if ('children' in newNodeCopy) { + if (('children' in newNodeCopy) && (!!node.children.length || !!newNodeCopy.children?.length)) { // remove all children this.removeChildren(key, false, false) // add new children if (Array.isArray(newNodeCopy.children)) { - this.loadChildren(this.mapData[key], newNodeCopy.children, this.mapData[key].expand) + this.loadChildren(node, newNodeCopy.children, node.expand) } delete newNodeCopy.children @@ -537,7 +538,7 @@ export default class TreeStore extends TreeEventTarget { delete newNodeCopy.expand } Object.keys(newNodeCopy).forEach((field) => { - this.mapData[key][field] = newNodeCopy[field] + node[field] = newNodeCopy[field] }) const currentCheckedKeys = this.getCheckedKeys() @@ -554,6 +555,9 @@ export default class TreeStore extends TreeEventTarget { } if (triggerDataChange) { + if (triggerSetDataFlag) { + this.emit('set-data') + } this.emit('visible-data-change') } } @@ -564,9 +568,15 @@ export default class TreeStore extends TreeEventTarget { const previousCheckedKeys = this.getCheckedKeys() const previousSelectedKey = this.getSelectedKey() + let triggerSetDataFlag = false - validNodes.forEach((node) => { - this.updateNode(node[this.options.keyField], node, false, false) + validNodes.forEach((newNode) => { + const key = newNode[this.options.keyField] + const node = this.mapData[key] + if (node) { + triggerSetDataFlag = triggerSetDataFlag || this.isChildrenChanged(node, newNode) + this.updateNode(key, newNode, false, false) + } }) const currentCheckedKeys = this.getCheckedKeys() @@ -580,6 +590,10 @@ export default class TreeStore extends TreeEventTarget { this.triggerSelectedChange(true, false) } + if (triggerSetDataFlag) { + this.emit('set-data') + } + this.emit('visible-data-change') } @@ -894,6 +908,7 @@ export default class TreeStore extends TreeEventTarget { if (!node || !node.children.length) return null const firstChild = node.children[0] + let movingNode = firstChild // 从 flatData 中移除 const index = this.findIndex(node) @@ -905,6 +920,11 @@ export default class TreeStore extends TreeEventTarget { // 从 mapData 中移除 delete this.mapData[this.flatData[i][this.options.keyField]] deleteCount++ + + // 如果是 Selected 的节点,则记录 + if (this.flatData[i].selected) { + movingNode = this.flatData[i] + } } else break } this.flatData.splice(index + 1, deleteCount) @@ -915,7 +935,7 @@ export default class TreeStore extends TreeEventTarget { node.indeterminate = false // 更新被移除处父节点状态 - this.updateMovingNodeStatus(firstChild, triggerEvent, triggerDataChange) + this.updateMovingNodeStatus(movingNode, triggerEvent, triggerDataChange) if (triggerDataChange) { this.emit('visible-data-change') @@ -935,7 +955,7 @@ export default class TreeStore extends TreeEventTarget { const currentCheckedKeys = this.getCheckedKeys() const flattenChildren = this.flattenData( node.children, - this.getSelectedKey === null + this.getSelectedKey() === null ) this.insertIntoFlatData(parentIndex + 1, flattenChildren) // 如果有未加载的选中节点,判断其是否已加载 @@ -943,6 +963,8 @@ export default class TreeStore extends TreeEventTarget { if (this.unloadSelectedKey !== null) { this.setUnloadSelectedKey(this.unloadSelectedKey) } + + this.checkNodeUpward(node, true) } private getInsertedNode( @@ -1168,8 +1190,6 @@ export default class TreeStore extends TreeEventTarget { if (node.checked && this.options.cascade) { // 向下勾选,包括自身 this.checkNodeDownward(node, true) - // 向上勾选父节点直到根节点 - this.checkNodeUpward(node) } if (node.selected && overrideSelected) { @@ -1191,6 +1211,12 @@ export default class TreeStore extends TreeEventTarget { this.flattenData(node.children, overrideSelected, result) } } + + if (this.options.cascade && !!length) { + // 向上勾选父节点直到根节点 + this.checkNodeUpward(nodes[0]) + } + return result } @@ -1230,9 +1256,10 @@ export default class TreeStore extends TreeEventTarget { /** * 向上勾选/取消勾选父节点,不包括自身 * @param node 需要勾选的节点 + * @param fromCurrentNode 是否从当前节点开始处理 */ - private checkNodeUpward(node: TreeNode) { - let parent = node._parent + private checkNodeUpward(node: TreeNode, fromCurrentNode = false) { + let parent = fromCurrentNode ? node : node._parent while (parent) { this.checkParentNode(parent) parent = parent._parent diff --git a/tests/unit/tree.spec.ts b/tests/unit/tree.spec.ts index 7050458..f342c34 100644 --- a/tests/unit/tree.spec.ts +++ b/tests/unit/tree.spec.ts @@ -168,7 +168,7 @@ describe('树展示测试', () => { ).toBe(true) expect( treeNodes[1].find('.vtree-tree-node__checkbox_indeterminate').exists() - ).toBe(true) + ).toBe(false) expect( treeNodes[2].find('.vtree-tree-node__title_selected').exists() ).toBe(true)