[UTree] How to programmatically select UTree item? #6619
Unanswered
KazimirPodolski
asked this question in
Q&A
Replies: 1 comment
|
There is no public imperative API on
So I would make the route sync data-driven: const selected = ref<TreeItem[]>([])
const expanded = ref<string[]>([])
const itemById = new Map<string, TreeItem>()
const parentById = new Map<string, TreeItem | null>()
function indexTree(items: TreeItem[], parent: TreeItem | null = null) {
for (const item of items) {
itemById.set(item.id, item)
parentById.set(item.id, parent)
if (item.children?.length) indexTree(item.children, item)
}
}
indexTree(items)
function ancestors(id: string) {
const result: TreeItem[] = []
let parent = parentById.get(id)
while (parent) {
result.unshift(parent)
parent = parentById.get(parent.id)
}
return result
}
function selectionFromRoute(id: string) {
const item = itemById.get(id)
if (!item) return []
const value = [item]
const selectedIds = new Set([item.id])
// Reproduce bubbleSelect for the controlled value.
for (const parent of ancestors(id).reverse()) {
const allChildrenSelected = parent.children?.every(child => selectedIds.has(child.id))
if (allChildrenSelected) {
value.push(parent)
selectedIds.add(parent.id)
}
}
return value
}
watch(
() => route.params.id,
(id) => {
if (typeof id !== 'string') return
selected.value = selectionFromRoute(id)
expanded.value = ancestors(id).map(item => item.id)
},
{ immediate: true }
)<UTree
v-model="selected"
v-model:expanded="expanded"
:items="items"
multiple
bubble-select
selection-behavior="replace"
:get-key="item => item.id"
/>Two practical notes:
|
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Package
v4.x
Description
I need to synchronize selected item(s) in my Tree with current route. So when an item
id=123is selected, the route is#/items/123. Worst of all, I need it withmultiple+bubbleSelect+selectionBehavior="replace".You can imagine a file manager where Tree is the filesystem and current route is the filepath.
Item selected -> update route is obvious to me:
But how do I do the opposite? Route is updated -> select current item:
The issue above is I cannot simply put a
TreeItemintoselected.valueas it must be the whole path from the item to tree root due tobubbleSelect. Looking at the source, Reka actually builds a tree structure internally and maintainsparentprop which would make selecting withbubbleSelecteasy, but it's not exposed outside.One alternative is to give up on the "tree" aspect of UTree and completely make the tree structure myself. But I would like to reuse UTree to the max if possible.
All reactions