Rafael
Rafael

Reputation: 340

How to expand all item in a TreeSelect from Sakai PrimeVUE?

I'm using TreeSelect from Sakai PrimeVUE template, I would like to keep all items expanded on open the component, but could not find this option in the documentation.

My TreeSelect implementation:

<TreeSelect v-model="product.category" :overlayVisible="true" selectionMode="single"  :options="categories" @change="categoryChange(product)"></TreeSelect>

Info from my package.json:

"primevue": "^3.11.0",
"vue": "3.2.9",

Upvotes: 1

Views: 1782

Answers (1)

tony19
tony19

Reputation: 138526

TreeSelect has a method named expandPath(path), where path is the key property in a tree node.

To expand all nodes, collect all the keys from the tree nodes, and then pass each of them to expandPath():

  1. Add a template ref on <TreeSelect> to use it later in script:
<script setup>
import { ref } from 'vue'

const treeRef = ref()
const treeNodes = ref()
</script>

<template>
  <TreeSelect ref="treeRef" :nodes="treeNodes" ⋯ />
</template>
  1. Create a method (e.g., named getKeysFromTree) to extract the keys from an array of tree nodes:
const getKeysFromNode = (node) => {
  const keys = [node.key]
  if (node.children) {
    keys.push(...node.children.flatMap(getKeysFromNode))
  }
  return keys
}

const getKeysFromTree = (tree) => tree.flatMap(getKeysFromNode)
  1. In an onMounted() hook, use the template ref to call expandPath() on each of the tree's keys (extracted with getKeysFromTree() defined above):
<script setup>
import { onMounted } from 'vue'

onMounted(() => {
  const data = /* tree nodes data */
  treeNodes.value = data
  getKeysFromTree(data).forEach((key) => treeRef.value.expandPath(key))
})
</script>

demo

Upvotes: 2

Related Questions