Skip to content

shadcn.io is an independent project built on shadcn/ui

Components

Free

Command for Vue UI SDK

A command palette for Vue on UI SDK: a search field that narrows a list of actions as you type, with groups, shortcut hints and a dialog.

On this page9 sections

Command puts a search field above a list of actions. People type a few letters, the list narrows to the rows that match, and Enter runs the highlighted one. Open it in a dialog on Cmd+K as an app-wide command palette, or keep it inline at the top of a sidebar or a menu.

When the pick is a value a form keeps, such as a country or an assignee, use a Combobox. A short menu with nothing to search reads better as a Dropdown Menu.

Preview width

Installation

Sign in to get your install command
Free with an account. It carries your token, so the CLI installs everything in one go.

Anatomy

Command anatomy: root, input, group label, list, item, shortcut

Usage

<script setup lang="ts">
import { computed, unref } from "vue"
import { useFilter, useListCollection } from "@/lib/list-collection"
import {
  CalculatorIcon, CalendarIcon, CreditCardIcon, SettingsIcon, SmileIcon,
  UserIcon,
} from "lucide-vue-next"
import {
  Command, CommandContent, CommandEmpty, CommandGroup, CommandInput,
  CommandItem, CommandList, CommandSeparator, CommandShortcut,
} from "@/components/ui/command"

const initialItems = [
  {
    group: "Suggestions",
    icon: CalendarIcon,
    label: "Calendar",
    value: "calendar",
  },
  {
    group: "Suggestions",
    icon: SmileIcon,
    label: "Search Emoji",
    value: "emoji",
  },
  {
    disabled: true,
    group: "Suggestions",
    icon: CalculatorIcon,
    label: "Calculator",
    value: "calculator",
  },
  {
    group: "Settings",
    icon: UserIcon,
    label: "Profile",
    shortcut: "⌘P",
    value: "profile",
  },
  {
    group: "Settings",
    icon: CreditCardIcon,
    label: "Billing",
    shortcut: "⌘B",
    value: "billing",
  },
  {
    group: "Settings",
    icon: SettingsIcon,
    label: "Settings",
    shortcut: "⌘S",
    value: "settings",
  },
];

const filterApi = useFilter({ sensitivity: "base" })

const { collection, filter } = useListCollection<(typeof initialItems)[number]>(computed(() => ({
  filter: unref(filterApi).contains,
  groupBy: (item) => item.group,
  initialItems,
})))

const handleInputValueChange = (inputValue: string) => {
  filter(inputValue);
}
</script>

<template>
  <Command
    class="max-w-sm rounded-lg border"
    :collection="collection"
    @input-value-change="handleInputValueChange"
  >
    <CommandInput placeholder="Type a command or search..." />
    <CommandContent>
      <CommandList>
        <CommandEmpty>No results found.</CommandEmpty>
        <template v-for="([group, items], index) in collection.group()" :key="group">
          <CommandSeparator v-if="index > 0" />
          <CommandGroup :heading="group">
            <CommandItem v-for="item in items" :item="item" :key="item.value">
              <component :is="item.icon" aria-hidden="true" />
              <span>{{ item.label }}</span>
              <CommandShortcut v-if="!!item.shortcut">
                {{ item.shortcut }}
              </CommandShortcut>
            </CommandItem>
          </CommandGroup>
        </template>
      </CommandList>
    </CommandContent>
  </Command>
</template>

Accessibility

Focus stays in the search field while the arrow keys move a highlight through the list, and the field points at the highlighted row with aria-activedescendant, so a screen reader reads each row as it's reached. The field has the combobox role, and the list is a listbox of options that takes its name from the field. Once typing pauses, a screen reader hears how many rows match. CommandInput takes its accessible name from its placeholder, or "Search" without one. CommandDialogContent gives the dialog a title only screen readers hear, "Command Palette" unless you set title. The icons are decoration, so keep them aria-hidden as the demos do.

Arrow Down
Highlights the next item, skipping disabled ones, and stays on the last one unless you add loop to Command.
Arrow Up
Highlights the previous item, skipping disabled ones, and stays on the first one unless you add loop to Command.
Command+Arrow Down
Highlights the last item. Cmd + ArrowDown on a Mac.
Command+Arrow Up
Highlights the first item. Cmd + ArrowUp on a Mac.
Page Down
Moves the highlight ten items down.
Page Up
Moves the highlight ten items up.
Ctrl+N
On a Mac, highlights the next item, as ArrowDown does.
Ctrl+P
On a Mac, highlights the previous item, as ArrowUp does.
Enter
Runs the highlighted item, as a click does. The search field keeps its text.
Escape
Clears the search field. When it's already empty, closes CommandDialog.

Demos

Basic

An Open Menu button opens a dialog with three suggestions, Calendar, Search Emoji and Calculator, under a field that narrows them as you type. A short message takes the rows' place when nothing matches. Start here for a palette over a few actions, or leave out the dialog to keep the list on the page, like the menu at the top.

Preview width

Shortcuts

Profile, Billing and Settings, each with an icon and a CommandShortcut at the end of the row showing ⌘P, ⌘B or ⌘S. The hint is text, and nothing in this demo listens for those keys. Show hints when the actions already have shortcuts elsewhere in your app, so the palette teaches them, and bind the keys yourself.

Preview width

Groups

Suggestions and Settings sit under their own headings with a separator between them, an icon on every row and shortcut hints on the settings rows. Each item names its group, groupBy in useListCollection reads that field, and collection.group() returns the sections. Group the commands once they fall into more than one kind, such as places to go and things to do.

Preview width

Scrollable

Twenty-three commands in five groups, from Navigation and Actions down to Account and Tools, more than the dialog can show at once. The list stops at 18rem and scrolls with its scrollbar hidden, while the search field stays at the top. At this length a few typed letters beat scrolling, and the headings help the people who scroll anyway.

Preview width

Palette

Cmd+K on a Mac or Ctrl+K elsewhere toggles the palette from anywhere on the page, and a Search button opens it for pointer and touch users. Pages and Actions are grouped, and a footer names the keys for moving, picking and closing. Picking a row writes its name under the button and closes the dialog, which is the wiring an app-wide palette needs.

Preview width

RTL

The inline menu from the top of the page in Arabic, with dir set to rtl on both Command and CommandInput. Headings, labels, the placeholder and the empty message are translated, the calculator row stays disabled, and the shortcut hints move to the inline end of each row, on the left. Use it to check the filter and the separators in a right-to-left layout.

Preview width

FAQ

How do I open the Command palette with Cmd+K in Vue?

Listen for the shortcut on document yourself, because the component binds no keys of its own. In the keydown handler, check that the key is k and that metaKey or ctrlKey is down, call preventDefault() so the browser doesn't act on the keys too, and flip the open state you pass to CommandDialog.

Add the listener when the component mounts and remove it when it unmounts. The Palette demo does exactly this, and keeps a Search button on the page for phones, where there is no shortcut to press.

How do I run an action when a Command item is selected?

Listen to @select on Command. It fires on every pick, by click or Enter, with the row's value as its first argument. The Palette demo uses @value-change instead, with :value held at null so that picking the same row twice still fires, and looks the whole item up in the collection with find.

Navigating works the same way: go to the route in that handler, then close the dialog so the page underneath is what people see.

Should I use a Command or a Combobox?

Use a Command when picking a row does something: it opens a page, runs an action or flips a setting, the way a command palette or a searchable action menu works. The search is a way to reach the action, and nothing needs to remember which row was chosen.

Use a Combobox when the pick is a value that stays in a form field afterwards, like a country or an assignee, and goes out with the form when it's submitted.

How do I change how the Command filters and ranks items?

With a collection, as in every demo here, the filtering is yours: Command shows the items you pass, and the demos narrow them with useListCollection. Its filter option decides what matches, here contains from useFilter, which ignores case and accents and tests each item's label.

Swap in startsWith from the same hook, or write a function that also reads the item, its third argument, to match on aliases. Without a collection, Command filters the items you write as cmdk does, on each one's value or text plus its keywords, and filter on Command takes contains, startsWith or a scoring function in place of the fuzzy default.

How do I load Command results from an API as the user types?

Fetch in @input-value-change on Command, then put the response in the collection with set from useListCollection, which replaces the items. Leave out the hook's filter option so the server's results show as they come back.

While a request is in flight, pass status="loading" to Command, which marks the list busy for screen readers, and have CommandEmpty say so, or it reports no results before any have arrived.

Why doesn't pressing a Command shortcut do anything?

CommandShortcut is a label and nothing more. It prints the keys at the end of the row, but no code listens for them, in the palette or anywhere else.

Bind each one yourself with a keydown listener on document, the way the Palette demo binds Cmd+K, and have it call the same function the row runs when it's picked. Keeping both in one place stops a hint from naming keys that do something else. Or give the CommandItem a shortcut and UI SDK runs the row on those keys, with an empty CommandShortcut showing them, though only while the list is on the page.

How do I show a message when no Command results match?

Put a CommandEmpty inside CommandList. UI SDK keeps it in the page as a live region and fills it only while no item is left to show, so a screen reader hears the message when it appears, once, in place of UI SDK's own "No results". Without children it says "No results found." Give it your own words, such as a hint to try another term or a link to the full search.

API Reference

Command

<div> data-slot="command"

PropType
pages?string[]

The stack of open pages, from the first page opened to the current one. Pass it to control it. Two-way with v-model:pages.

defaultPages?string[]

The pages open at first, when uncontrolled.

Default
[]
query?string

The search text, which filters the commands. Pass it to control it. Two-way with v-model:query.

defaultQuery?string

The search text at first, when uncontrolled.

Default
""
value?string | null

The highlighted command's value. Pass it to control the highlight. null highlights nothing. Two-way with v-model.

Type
string | null
defaultValue?string | null

The command highlighted at first, when uncontrolled. Without it, the first command is, with autoHighlight.

Type
string | null
announcement?(change: ListAnnouncement) → string | null

What screen readers hear after typing pauses, when no CommandStatus is rendered. Return null for nothing.

Type
(change: ListAnnouncement) → string | null
Default
"3 results", "No results" or "Loading"
Parameters

change – ListAnnouncement

Returns
string | null
autoHighlight?boolean

Whether the first command is highlighted while nothing else is, and the best match as the user types, so Enter runs it.

Default
true
controller?CommandController

Reads and drives the list from anywhere. Create one with createCommandController().

debug?boolean

Logs every state change with its reason to the console, in development builds.

emptyItems?CommandData

Commands shown instead of items on the first page while the search is empty, like recent or suggested ones. Groups work, like { type: "group", label: "Suggestions", items }. Needs items.

filter?"fuzzy" | "contains" | "startsWith" | CommandFilter

How typing narrows the list: "fuzzy", "contains", "startsWith", or cmdk's function of an item's value, the search and its keywords, which returns a score (0 hides the item).

Type
"fuzzy" | "contains" | "startsWith" | CommandFilter
Default
"fuzzy"
items?CommandData

The commands as data. Renders them for you, ranked as the user types, with pages for commands that have items.

label?string

Names the search field, for screen readers (cmdk's label).

loop?boolean

Whether the arrow keys wrap from the last item to the first.

Default
false
pendingAnnouncement?string

What screen readers hear once a command has been pending for a second, so a slow action doesn't pass in silence. Set it in the page's language. An empty string says nothing.

Default
"Loading"
shouldFilter?boolean

Whether typing filters the items. Turn it off for results you filter yourself, like a server's.

Default
true
status?AsyncOptionsStatus

Whether results are loading or failed, for the empty and status parts. Sets aria-busy on the list while loading.

Default
"idle"
#render?{ props, state, children }

A slot that renders your own element: bind its props with v-bind="props". It also gets the part's state, and children, its content.

class?string

Merged with the part's classes.

EventType
@pages-change(pages: string[], details: ChangeDetails<CommandPagesChangeReason>) → void

Runs when a page opens or Backspace or Escape goes back.

Type
(pages: string[], details: ChangeDetails<CommandPagesChangeReason>) → void
Parameters

pages – string[]

details – ChangeDetails<CommandPagesChangeReason>

Returns
void
@query-change(query: string, details: TextChangeDetails<CommandQueryChangeReason>) → void

Runs when the search text wants to change: typing, opening a page, going back, or a controller.

Type
(query: string, details: TextChangeDetails<CommandQueryChangeReason>) → void
Parameters

query – string

details – TextChangeDetails<CommandQueryChangeReason>

Returns
void
@value-change(value: string | null, details: CommandValueChangeDetails) → void

Runs when the highlight moves: arrow keys, the pointer, typing, a page change or a controller. details.index says where the command is, for virtualized lists.

Type
(value: string | null, details: CommandValueChangeDetails) → void
Parameters

value – string | null

details – CommandValueChangeDetails

Returns
void
@action(value: string, details: CommandActionDetails) → unknown

Runs when a command runs, with its value: Enter, a click, or its shortcut. Return a Promise to mark the command pending until it settles: it gets data-pending, aria-busy and aria-disabled, and running it again waits. A rejection puts the reason in its error state until the next run.

Type
(value: string, details: CommandActionDetails) → unknown
Parameters

value – string

details – CommandActionDetails

Returns
unknown
@load-more() → void

Runs when the highlight or scrolling reaches the last command, so the next page can load, like createAsyncOptions's loadMore. Not again for the same commands, unless the last load failed.

Returns
void
AttributeType
data-loading?string

Present while results load, with status="loading".

CommandDialog

PropType
open?boolean

Whether the dialog is open. Pass it to control the dialog. Two-way with v-model or v-model:open.

defaultOpen?boolean

Whether the dialog starts open, when uncontrolled. Focus moves into it once it's on the page.

Default
false
closeOnOutsidePress?boolean

Whether pressing outside the dialog, like on its backdrop, closes it. The press counts once it's released outside too, so dragging a text selection out of a field doesn't close it.

Default
true, or false when `modal` is false
container?DocumentFragment | Element | null

Renders the popup into this element instead of in place, like a container inside a shadow root or an iframe. On web components, a CSS selector. Nested popups stay inside their parent.

Type
DocumentFragment | Element | null
controller?PopupController<any, DialogOpenChangeReason, {}, any, DialogPayloadChangeReason>

Opens, closes and inspects the dialog from anywhere, and connects triggers outside it. Create one with createDialogController().

Type
PopupController<any, DialogOpenChangeReason, {}, any, DialogPayloadChangeReason>
debug?boolean

Logs every state change with its reason to the console, in development builds.

description?string

The dialog's description, for screen readers.

Default
"Search for a command to run..."
dismissible?boolean

Whether Escape, an outside press and Android's back gesture can close the dialog. Close parts, triggers and the controller always can. Pass false while a form has unsaved changes, and ask in onDismissAttempt.

Default
true
modal?"trap-focus" | boolean

true: the rest of the page is inert and doesn't scroll, focus is trapped, and an outside press only closes the dialog. "trap-focus": traps focus, and leaves the page scrollable and clickable. false: a dialog beside the page, which Tab can leave and outside presses don't close.

Type
"trap-focus" | boolean
Default
true
pendingAnnouncement?string

What screen readers hear once a Close part's action has been running for a second, so a slow action doesn't pass in silence. Set it in the page's language. An empty string says nothing.

Default
"Loading"
persistentElements?(string | Element)[] | (() → Element[])

Elements that stay usable while the dialog makes the page inert, like a chat launcher or a password manager's button. Elements, CSS selectors, or a function that returns elements, read when the dialog opens. Presses on them never close it.

Type
(string | Element)[] | (() → Element[])
Parameters

string | Element)[] | ((

Returns
Element[])
presentation?PresentationSetting<"dialog">

How the dialog presents. "sheet" slides it up from the bottom of the screen, where it can be swiped away, and "auto" does that on small touch screens. Decided each time it opens; the server renders "dialog" for "auto".

Type
PresentationSetting<"dialog">
Default
"dialog"
showCloseButton?boolean

Shows the close button in the corner.

Default
false
title?string

The dialog's title, for screen readers.

Default
"Command Palette"
class?string

Merged with the part's classes.

EventType
@open-change(open: boolean, details: DialogOpenChangeDetails) → void

Runs when the dialog wants to open or close. details.reason says why, details.cancel() stops it, and details.returnValue carries what closed it.

Type
(open: boolean, details: DialogOpenChangeDetails) → void
Parameters

open – boolean

details – DialogOpenChangeDetails

Returns
void
@dismiss-attempt(details: DialogDismissAttemptDetails) → void

Runs when a dismissal was refused, because dismissible is false, an outside press doesn't close it, or a Close part's action is running. Ask "Discard changes?" here.

Type
(details: DialogDismissAttemptDetails) → void
Parameters

details – DialogDismissAttemptDetails

Returns
void
@open-change-complete(open: boolean) → void

Runs once the dialog has finished opening or closing, after any animation.

Parameters

open – boolean

Returns
void
@payload-change(payload: unknown, details: ChangeDetails<DialogPayloadChangeReason>) → void

Runs when the payload the content shows changes: a trigger with another payload opens the dialog, or takes a non-modal dialog over while it's open, which fires no onOpenChange, and so does a controller's open({ payload }) on the open dialog. details.cancel() keeps the previous payload.

Type
(payload: unknown, details: ChangeDetails<DialogPayloadChangeReason>) → void
Parameters

payload – unknown

details – ChangeDetails<DialogPayloadChangeReason>

Returns
void

CommandInput

<div> data-slot="command-input-wrapper"

PropType
value?string

The search, to control it from the field (cmdk's API). Two-way with v-model.

#render?{ props, state, children }

A slot that renders your own element: bind its props with v-bind="props". It also gets the part's state, and children, its content.

class?string

Merged with the part's classes.

EventType
@value-change(search: string) → void

Runs as the search changes.

Parameters

search – string

Returns
void

CommandList

<div> data-slot="command-list"

PropType
#render?{ props, state, children }

A slot that renders your own element: bind its props with v-bind="props". It also gets the part's state, and children, its content.

class?string

Merged with the part's classes.

AttributeType
data-has-icons?string

Present while any command inside holds an icon part, so items without one can line up.

CommandEmpty

<div> data-slot="command-empty"

PropType
#render?{ props, state, children }

A slot that renders your own element: bind its props with v-bind="props". It also gets the part's state, and children, its content.

class?string

Merged with the part's classes.

AttributeType
data-empty?string

Present while no command matches.

data-loading?string

Present while results load, with status="loading".

CommandGroup

<div> data-slot="command-group"

PropType
heading?VNode

The group's heading, which names it.

#render?{ props, state, children }

A slot that renders your own element: bind its props with v-bind="props". It also gets the part's state, and children, its content.

class?string

Merged with the part's classes.

CommandSeparator

<div> data-slot="command-separator"

PropType
#render?{ props, state, children }

A slot that renders your own element: bind its props with v-bind="props". It also gets the part's state, and children, its content.

class?string

Merged with the part's classes.

CommandItem

<div> data-slot="command-item"

PropType
disabled?boolean

Keeps the command from running. Arrow keys and the pointer skip it. Sets data-disabled and aria-disabled.

index?number

The command's position among all visible commands, for virtualized lists that render only some. Sets aria-posinset and aria-setsize.

keywords?string[]

More words the search matches.

label?string

The text the search matches, when the content isn't plain text. Not the accessible name: use aria-label for that.

page?string

The page choosing this command opens, by the value of a CommandPage.

shortcut?string

A keyboard shortcut that runs the command while it's in the page, like "mod+p". Sets aria-keyshortcuts, and a CommandShortcut inside shows it.

value?string

Passed to onAction and onValueChange, and identifies the command. Without it, one is generated.

#render?{ props, state, children }

A slot that renders your own element: bind its props with v-bind="props". It also gets the part's state, and children, its content.

class?string

Merged with the part's classes.

EventType
@select(value: string) → unknown

Runs when the item runs, by a press or Enter, with its value: value, or its text without one. A Promise marks it pending until it settles.

Parameters

value – string

Returns
unknown
AttributeType
data-disabled?string

Present when the command can't run. Arrow keys skip it.

data-has-icon?string

Present on a command while it holds an icon part.

data-highlighted?string

Present on the highlighted command, which Enter runs. Focus stays in the field.

data-pending?string

Present while the Promise the command's onSelect or onAction returned is running.

CommandShortcut

<span>

PropType
shortcut?string

The keys to show, like "mod+p". Inside a command, its shortcut.

#render?{ props, state, children }

A slot that renders your own element: bind its props with v-bind="props". It also gets the part's state, and children, its content.

class?string

Merged with the part's classes.