PXD
v0.2.1-dev

Tree

Tree view driven by the data prop, with expandable parents and single or cascading multiple selection.

Default

docs
<script setup>
import { ref } from 'vue'

const value = ref(null)

const data = [
  {
    label: 'src',
    value: 'src',
    children: [
      { label: 'components', value: 'components', children: [{ label: 'tree', value: 'tree' }] },
      { label: 'composables', value: 'composables' },
    ],
  },
  { label: 'docs', value: 'docs' },
]
</script>

<template>
  <PTree v-model="value" class="w-72 max-h-64" :data="data" />
</template>

Multiple

A shift-click takes the span between two rows in document order, starting where the selection last landed; a further one moves that span, and a disabled row is neither an end nor part of one.

docs
<script setup>
import { ref } from 'vue'

const value = ref([])

const data = [
  {
    label: 'src',
    value: 'src',
    children: [
      { label: 'components', value: 'components' },
      { label: 'composables', value: 'composables' },
      { label: 'context', value: 'context' },
      { label: 'utils', value: 'utils' },
    ],
  },
  { label: 'docs', value: 'docs' },
]
</script>

<template>
  <PTree v-model="value" class="w-72 max-h-64" multiple :data="data" />
</template>

Independent selection

Every node is selected on its own: no cascading, no partial state.

src
components
composables
docs
<script setup>
import { ref } from 'vue'

const value = ref(['composables'])

const data = [
  {
    label: 'src',
    value: 'src',
    children: [
      { label: 'components', value: 'components' },
      { label: 'composables', value: 'composables' },
    ],
  },
  { label: 'docs', value: 'docs' },
]
</script>

<template>
  <PTree
    v-model="value"
    class="w-72 max-h-64"
    multiple
    check-strictly
    :data="data"
    :default-expanded-keys="['src']"
  />
</template>

Selectable nodes

A refused node keeps its row, expands and takes drops; only its checkbox greys out, and a click leaves the selection alone. Under multiple it is never checked by a click, but a partial subtree still marks it, and one the model already carries stays checked.

src
index.vue
tree
utils.ts
README.md
<script setup>
import { ref } from 'vue'

const value = ref([])

const data = [
  {
    label: 'src',
    value: 'src',
    children: [
      { label: 'index.vue', value: 'index.vue', saved: true },
      { label: 'tree', value: 'tree', saved: true },
      { label: 'utils.ts', value: 'utils.ts' },
    ],
  },
  { label: 'README.md', value: 'README.md' },
]
</script>

<template>
  <PTree
    v-model="value"
    class="w-72 max-h-64"
    multiple
    :data="data"
    :default-expanded-keys="['src']"
    :selectable="(node) => !node.saved"
  />
</template>

Expand only

A parent row becomes a handle for its subtree: the click opens or closes it, and under multiple only the checkbox selects. To refuse a node whatever is clicked, reach for selectable.

README.md
<script setup>
import { ref } from 'vue'

const value = ref()

const data = [
  {
    label: 'src',
    value: 'src',
    children: [
      { label: 'index.vue', value: 'index.vue' },
      { label: 'tree', value: 'tree', children: [{ label: 'types.d.ts', value: 'types.d.ts' }] },
    ],
  },
  { label: 'README.md', value: 'README.md' },
]
</script>

<template>
  <PTree v-model="value" class="w-72 max-h-64" expand-only :data="data" />
</template>

Disabled

A disabled node is skipped by the keyboard, but its arrow still expands it.

src
components
locked
<script setup>
const data = [
  {
    label: 'src',
    value: 'src',
    children: [
      { label: 'components', value: 'components' },
      { label: 'locked', value: 'locked', disabled: true },
    ],
  },
]
</script>

<template>
  <PTree class="w-72 max-h-64" multiple :data="data" :default-expanded-keys="['src']" />
</template>

A match keeps its ancestor chain visible. The query owns expansion while it is active: the arrows only mark where the hits sit, and toggling resumes once it is cleared. Replacing the content through node-content also means drawing the highlight-match mark yourself: the slot receives parts, the label split into { text, matched } runs.

readme.md
<script setup>
const data = [
  {
    label: 'src',
    value: 'src',
    children: [
      { label: 'components', value: 'components', children: [{ label: 'tree', value: 'tree' }] },
      { label: 'composables', value: 'composables' },
    ],
  },
  { label: 'readme.md', value: 'readme' },
]
</script>

<template>
  <PTree class="w-72 max-h-64" filterable highlight-match :data="data">
    <template #empty>No match.</template>
  </PTree>
</template>

Giving remote-filter turns the search remote: a non-empty query goes to it 200ms after the last keystroke instead of through the local filter-method. It hands back the matched nodes with their ancestors, and that forest replaces data while the query is active, at its real depths with the chains to a hit opened; search-matches-only flattens it. Only the latest answer counts, and the field spins from the keystroke until one lands: before the first answer the empty slot covers the gap, after it the previous forest stays until the next arrives. Clearing the query restores data.

docs
<script setup>
const source = [
  {
    label: 'src',
    value: 'src',
    children: [
      { label: 'components', value: 'components', children: [{ label: 'tree', value: 'tree' }] },
      { label: 'composables', value: 'composables' },
    ],
  },
  { label: 'docs', value: 'docs' },
]

// A real one would ask a server; the shape it hands back is the same either way.
function search(query) {
  return new Promise((resolve) => {
    setTimeout(() => resolve(keepMatched(source, query)), 500)
  })
}

function keepMatched(nodes, query) {
  const result = []

  for (const node of nodes) {
    const children = keepMatched(node.children ?? [], query)

    if (children.length || node.label.includes(query)) {
      result.push(children.length ? { ...node, children } : { ...node, children: undefined })
    }
  }

  return result
}
</script>

<template>
  <PTree class="w-72 max-h-64" filterable :data="source" :remote-filter="search" />
</template>

Virtual

The container needs a height.

<script setup>
const data = Array.from({ length: 2000 }, (_, index) => ({
  label: 'Folder ' + index,
  value: 'folder-' + index,
  children: [{ label: 'File ' + index, value: 'file-' + index }],
}))
</script>

<template>
  <PTree class="w-72" virtual :data="data" :height="240" :item-size="32" />
</template>

Controlled expansion

0 expanded

<script setup>
import { ref } from 'vue'

const expandedKeys = ref([])

const data = [
  { label: 'src', value: 'src', children: [{ label: 'tree', value: 'tree' }] },
]
</script>

<template>
  <PStack gap="2">
    <PTree
      :data="data"
      :expanded-keys="expandedKeys"
      class="w-72 max-h-64"
      @update:expanded-keys="expandedKeys = $event"
    />
    <PText size="sm">{{ expandedKeys.length }} expanded</PText>
  </PStack>
</template>

Keyboard

ArrowUp/ArrowDown move the active row, ArrowRight expands or enters a subtree, ArrowLeft collapses or jumps to the parent, Home/End jump to both ends, Enter/Space toggle the selection.

docs
<script setup>
const data = [
  { label: 'src', value: 'src', children: [{ label: 'tree', value: 'tree' }] },
  { label: 'docs', value: 'docs' },
]
</script>

<template>
  <PTree class="w-72 max-h-64" :data="data" />
</template>

Custom icons

The tree draws no icon of its own: a row shows one only if a slot provides it.

docs
<script setup>
const data = [
  { label: 'src', value: 'src', type: 'folder', children: [{ label: 'tree', value: 'tree', type: 'file' }] },
  { label: 'docs', value: 'docs', type: 'file' },
]
</script>

<template>
  <PTree class="w-72 max-h-64" :data="data">
    <template #node-switcher="{ expanded }">
      <span class="text-xs">{{ expanded ? '-' : '+' }}</span>
    </template>

    <template #node-icon="{ node, expanded, hasChildren }">
      <span class="text-xs">{{ node.type === 'file' ? '#' : expanded ? 'v' : '>' }}</span>
    </template>
  </PTree>
</template>

The hits are rendered alone, flattened to the top level, instead of together with their ancestors.

docs
<script setup>
const data = [
  {
    label: 'src',
    value: 'src',
    children: [
      { label: 'components', value: 'components' },
      { label: 'composables', value: 'composables' },
    ],
  },
  { label: 'docs', value: 'docs' },
]
</script>

<template>
<PTree
  class="w-72 max-h-64"
  filterable
  highlight-match
  search-matches-only
  :data="data"
/>
</template>

Drag and drop

A drop emits update:data with the next shape, so bind the tree with v-model:data. Dragging is off while searching, and drop-inside-leaf lets a childless row take the dragged node as its first child.

Touch and pen must hold still for 300ms before they drag, because a finger that moves at once is scrolling the page; a mouse starts on the first 5px. The tree never scrolls on its own, so a touch drag reaches only the rows in view.

docs
<script setup>
import { ref } from 'vue'

const data = ref([
  {
    label: 'src',
    value: 'src',
    children: [
      { label: 'components', value: 'components' },
      { label: 'composables', value: 'composables' },
    ],
  },
  { label: 'docs', value: 'docs' },
])
</script>

<template>
  <PTree v-model:data="data" draggable drop-inside-leaf class="w-72 max-h-64" />
</template>

Restricting where a node may land

A node never lands on itself or inside its own subtree, whatever the predicate returns.

src
tree
docs
lock
<script setup>
import { ref } from 'vue'

const data = ref([
  { label: 'src', value: 'src', children: [{ label: 'tree', value: 'tree' }] },
  { label: 'docs', value: 'docs' },
  { label: 'lock', value: 'lock', disabled: true },
])

function allowDrop({ targetValue, position }) {
  if (targetValue === 'lock') {
    return false
  }

  return position !== 'after' || targetValue !== 'docs'
}
</script>

<template>
  <PTree
    v-model:data="data"
    class="w-72 max-h-64"
    :allow-drop="allowDrop"
    :default-expanded-keys="['src']"
    draggable
  />
</template>
docs
<script setup>
import { ref } from 'vue'

const data = ref([
  { label: 'src', value: 'src', children: [{ label: 'tree', value: 'tree' }] },
  { label: 'docs', value: 'docs' },
])
</script>

<template>
  <PTree v-model:data="data" class="w-72 max-h-64" draggable>
    <template #node-drag-preview="{ node }">
      <span class="text-foreground-secondary">{{ node.label }}</span>
    </template>
  </PTree>
</template>

Imperative methods

docs
<script setup>
import { shallowRef } from 'vue'

const tree = shallowRef()

const data = [
  { label: 'src', value: 'src', children: [{ label: 'tree', value: 'tree' }] },
  { label: 'docs', value: 'docs' },
]
</script>

<template>
  <PStack gap="2">
    <PButton size="sm" @click="tree?.expandAll()"> Expand all </PButton>
    <PButton size="sm" @click="tree?.collapseAll()"> Collapse all </PButton>

    <PTree ref="tree" class="w-72 max-h-64" :data="data" />
  </PStack>
</template>

Loading

Set loading to cover the tree with a mask: the empty slot hides, the built-in search field shows a spinner, and the keyboard and the search input are ignored.

<script setup>
import { ref } from 'vue'

const loading = ref(true)
const data = []
</script>

<template>
  <PStack align="center">
    <PTree class="w-72 max-h-64" filterable :loading="loading" :data="data">
      <template #empty>No folders.</template>
    </PTree>

    <PButton size="sm" @click="loading = !loading"> Toggle </PButton>
  </PStack>
</template>

Lazy loading

With lazy, a node without children in data still shows an arrow, and the first time it opens load is called with what the tree knows about it (see TreeLoadDetail): resolve(children) puts them in the tree, while reject() leaves it unloaded so the next expand asks again. A node that resolved before is never asked twice, one marked isLeaf never at all, and one whose children already sit in data is passed over.

Only a non-empty children array marks a parent: children: [] is a leaf, and so is a node whose request resolved with nothing. isLeaf outranks both — true means a leaf whatever data holds, false keeps the arrow on a node that has no children yet, which is how a file tree tells an empty folder from a file.

expandAll() opens level by level: each request that lands brings the next level into view, so a whole lazy tree ends up open rather than only its first level.

Under draggable, nothing can be dropped inside a parent whose children the tree has not fetched yet; elsewhere the drop proposes the whole tree through update:data, loaded subtrees included.

docs
<script setup>
import { ref } from 'vue'

const data = ref([
  { label: 'src', value: 'src' },
  { label: 'docs', value: 'docs', isLeaf: true },
])

const children = {
  src: [
    { label: 'components', value: 'src/components' },
    { label: 'composables', value: 'src/composables' },
  ],
  'src/components': [{ label: 'tree', value: 'src/components/tree' }],
}

function load({ node }, resolve) {
  setTimeout(() => resolve(children[node.value] ?? []), 600)
}
</script>

<template>
  <PTree class="w-72 max-h-64" lazy :data="data" :load="load" />
</template>

Props

NameTypeDefaultDescription
dataTreeOptions() => []Tree data, see TreeOption
model-valueTreeModelValue-Selected value, an array when multiple is set
multiplebooleanfalseShow a checkbox and cascade the selection through the parents
check-strictlybooleanfalseKeep every node independently selectable, without cascading and without the partial state
show-switcherbooleantrueDraw the switcher column; hiding it drops the leaf spacer too, so indent sets where the row starts
show-checkboxbooleantrueDraw the built-in checkbox under multiple; a row click still checks
disabledbooleanfalseDisable the selection and the keyboard of the whole tree
selectable(node: TreeOption) => booleanevery nodeKeep a node out of the selection without disabling it
expand-onlybooleanfalseA row click only opens or closes a parent instead of selecting it; under multiple the checkbox selects
draggablebooleanfalseAllow a row to be dragged to another position; off while searching and when disabled
allow-drop(info: TreeDropInfo) => boolean-Decide whether a drop may land, replacing the built-in refusal of disabled rows
drop-inside-leafbooleanfalseLet a childless row take the dragged node as its first child
search-matches-onlybooleanfalseWhile searching, render the hits alone instead of the hits plus their ancestors
virtualbooleanfalseEnable virtualized rendering for large trees
item-sizenumber32Row height in px when virtual is enabled
over-scannumber4Extra rows rendered outside the viewport when virtual is enabled
heightnumber | string-Height of the tree, required by virtual
indentnumber16Indentation added per depth level in px
expanded-keysComponentValue[]-Controlled expanded nodes
default-expanded-keysComponentValue[][]Expanded nodes before the user changes them
accordionbooleanfalseKeep one node open per level: expanding a node closes its siblings
field-namesTreeFieldNames-Rename the fields read from a node: value, label, children, disabled, isLeaf
lazybooleanfalseFetch the children of a node when it first opens instead of reading them from data
load(detail: TreeLoadDetail, resolve: TreeLoadResolve, reject: TreeLoadReject) => void-Fetch the children of a node nothing else provided: resolve hands them over, reject leaves it for the next expand
loadingbooleanfalseCover the tree with a loading mask; the search input and the keyboard are ignored
filterablebooleanfalseRender the search field
filter-method(node: TreeOption, query: string) => booleanfuzzy matchPredicate deciding which node shows while the query is being typed
remote-filter(query: string) => TreeOptions | Promise<TreeOptions>-Search through it instead of the local filter-method: it returns the matched nodes with their ancestors, which replace data while the query is active. A rejection shows the error message and emits retry
error-textComponentText'Request failed. Click to reload'Default text of the remote search error, replaceable through the error slot
highlight-matchbooleanfalseMark the matched substring of the label; a fuzzy hit that is not a contiguous run stays unmarked
search-placeholderstring-Placeholder of the search field
search-valuestring-Controlled search query
default-search-valuestring''Search query before the user types
item-classComponentClass-Class merged into every rendered row

TreeOption

Fields are read through field-names: value, label, children, disabled and isLeaf by name unless it says otherwise.

NameTypeDescription
valuestring | numberIdentifier of the node, unique in the whole tree
labelstring | number | nullText of the node
childrenTreeOption[]Child nodes; only a non-empty array marks a parent, so an empty one leaves no arrow
isLeafbooleanOutranks the data: true is a leaf with no arrow, never handed to load. false keeps the arrow on a node that has no children yet
disabledbooleanIgnore selection and skip the node while navigating

TreeLoadDetail

NameTypeDescription
nodeTreeOptionThe node whose children are asked for
depthnumberDepth of the node, 0 at the top level
parentTreeOptionThe node holding it, absent at the top level

Events

NameTypeDescription
update:model-value(value: TreeModelValue) => voidEmitted when the selection changes.
update:data(data: TreeOptions) => voidEmitted when a drag is dropped, carrying the whole next tree.
move(detail: TreeMoveDetail) => voidEmitted when a drag is dropped, carrying where the node came from and landed.
change(detail: TreeChangeDetail, details: ChangeDetails) => voidEmitted when a node is checked or unchecked.
update:expandedKeys(keys: ComponentValue[]) => voidEmitted when a node is expanded or collapsed.
expand(detail: TreeNodeDetail) => voidEmitted when a node is expanded.
collapse(detail: TreeNodeDetail) => voidEmitted when a node is collapsed.
node-click(detail: TreeNodeDetail, event: MouseEvent) => voidEmitted when a row is clicked; a click that ends a drag stays silent.
node-contextmenu(detail: TreeNodeDetail, event: MouseEvent) => voidEmitted when a row is right-clicked; the browser menu is left alone, so the caller decides whether to preventDefault.
update:searchValue(query: string) => voidEmitted when the search field changes while not loading. Write it back through search-value to control the field.
retry() => voidEmitted when the remote search error is clicked; the rejected query is re-run first.
interface TreeNodeDetail {
  value: string | number
  node: TreeOption
}

interface TreeChangeDetail extends TreeNodeDetail {
  checked: boolean
  checkedValues: (string | number)[]
  halfCheckedValues: (string | number)[]
}

interface TreeMoveLocation {
  parentValue?: string | number
  index: number
}

interface TreeMoveDetail {
  value: string | number
  node: TreeOption
  from: TreeMoveLocation
  to: TreeMoveLocation & {
    targetValue: string | number
    position: 'before' | 'inside' | 'after'
  }
}

Slots

NameDescription
node-switcherExpand arrow, replaced by a spinner while a lazy node loads. Slot props: node, depth, expanded, loading.
node-iconNode icon, nothing is drawn without it. Slot props: node, depth, expanded, hasChildren.
node-contentNode text. Slot props: node, depth, hasChildren, parts (the label split for highlight-match, undefined when nothing is marked).
node-suffixContent appended to the row. Slot props: node, hasChildren.
node-drag-previewCard that follows the pointer while dragging. Slot props: node.
searchReplaces the search field.
errorError message shown when a remote search rejects; click it to emit retry.
emptyContent shown when the tree has no row, or the search matched nothing.

Methods

NameTypeDescription
focus() => voidFocus the tree so it receives the keyboard.
scrollToKey(value: ComponentValue) => voidScroll the row of the node into view.
setActiveKey(value: ComponentValue) => voidMove the active row to the node.
expandKey(value: ComponentValue) => voidExpand the node.
collapseKey(value: ComponentValue) => voidCollapse the node.
expandAll() => voidExpand every parent, an empty folder (isLeaf: false) included; under lazy each level opens as it lands.
collapseAll() => voidCollapse every node.
getCheckedKeys(leafOnly?: boolean, includeIndeterminate?: boolean) => ComponentValue[]Return the checked values in document order, only the leaves when leafOnly is set, optionally including the partially checked ones. Covers collapsed subtrees, the same set change reports.
getVisibleKeys() => ComponentValue[]Return the values of the visible rows.
getData(value: ComponentValue) => TreeOption | undefinedReturn the source node of a key, collapsed rows included.
activeIndexnumberIndex of the active row, -1 when there is none.

Source

Source