Skip to content

[UTree] How to programmatically select UTree item? #6456

Description

@KazimirPodolski

Package

v4.x

Description

I need to synchronize selected item(s) in my Tree with current route. So when an item id=123 is selected, the route is #/items/123. Worst of all, I need it with multiple+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:

<script>
const syncRoute = (item: TreeItem) => router.push({name: 'item', params: {id: item.id}})
</script>
<template>
<UTree @update:modelValue="syncRoute"/>
</template>

But how do I do the opposite? Route is updated -> select current item:

<script>
const syncRoute = (item: TreeItem) => router.push({name: 'item', params: {id: item.id}})

const selected = ref<TreeItem[]>([]);
watch(router.currentRoute, currentRoute => {
  const itemRoute = currentRoute.matched.find(candidate => candidate.name === 'item')
  if (itemRoute) {
    // how to select the item?
  }
})
</script>
<template>
<UTree @update:modelValue="syncRoute" v-model="selected"/>
</template>

The issue above is I cannot simply put a TreeItem into selected.value as it must be the whole path from the item to tree root due to bubbleSelect. Looking at the source, Reka actually builds a tree structure internally and maintains parent prop which would make selecting with bubbleSelect easy, 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requestedv4#4488

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions