Used with a component · Select
useListbox
The active option and keyboard engine behind <Select> and <Combobox>. Focus stays on the trigger or input, and aria-activedescendant points at the active option. The composable only tracks an index: it renders nothing and reads no DOM. <Select> adds the popover, filtering, virtualization and the option markup. Use it to build a listbox of your own with the same keyboard behavior.
Install
import { useListbox } from 'vael-ui'Examples
<script setup lang="ts">
import { shallowRef, useId } from 'vue'
import { useListbox } from 'vael-ui'
const fruits = [
{ label: 'Apple', value: 'apple' },
{ label: 'Banana', value: 'banana', disabled: true },
{ label: 'Cherry', value: 'cherry' },
]
const picked = shallowRef<string>()
const listboxId = useId()
const { activeIndex, activeId, onKeydown, point, optionId } = useListbox({
items: fruits,
getLabel: (fruit) => fruit.label,
isDisabled: (fruit) => !!fruit.disabled,
onSelect: (fruit) => (picked.value = fruit.value),
listboxId,
})
</script>
<template>
<div
tabindex="0"
role="combobox"
aria-expanded="true"
:aria-controls="listboxId"
:aria-activedescendant="activeId"
@keydown="onKeydown"
>
{{ picked ?? 'Pick a fruit' }}
</div>
<ul :id="listboxId" role="listbox">
<li
v-for="(fruit, index) in fruits"
:id="optionId(index)"
:key="fruit.value"
role="option"
:aria-selected="picked === fruit.value"
:aria-disabled="fruit.disabled"
:data-active="index === activeIndex || undefined"
@pointermove="point(index)"
>
{{ fruit.label }}
</li>
</ul>
</template>