@data-slot/select

中文文档
1.1.3发布于 2026/11/05MITTypeScriptESM + CJS构建来源已验证近 30 天下载 6049

A headless, accessible select component for choosing a single value from a dropdown list.

原始使用文档
文档目录16 节
  1. Installation
  2. Usage
  3. HTML Structure
  4. JavaScript
  5. API
  6. Initialization
  7. Slots
  8. Data Attributes
  9. Options
  10. Content mounting and server rendering
  11. Controller
  12. Events
  13. Keyboard Navigation
  14. Accessibility
  15. Form Integration
  16. License

@data-slot/select

A headless, accessible select component for choosing a single value from a dropdown list.

Installation

npm install @data-slot/select

Usage

HTML Structure

<div data-slot="select" data-placeholder="Choose a fruit...">
  <button data-slot="select-trigger">
    <span data-slot="select-value"></span>
    <!-- Add your own chevron icon -->
  </button>
  <div data-slot="select-content" hidden>
    <div data-slot="select-viewport">
      <div data-slot="select-group">
        <div data-slot="select-label">Fruits</div>
        <div data-slot="select-item" data-value="apple">
          <span data-slot="select-item-text">Apple</span>
        </div>
        <div data-slot="select-item" data-value="banana">
          <span data-slot="select-item-text">Banana</span>
        </div>
        <div data-slot="select-item" data-value="orange">
          <span data-slot="select-item-text">Orange</span>
        </div>
      </div>
      <div data-slot="select-separator"></div>
      <div data-slot="select-item" data-value="other">
        <span data-slot="select-item-text">Other</span>
      </div>
    </div>
  </div>
</div>

JavaScript

import { create, createSelect } from '@data-slot/select';

// Auto-discover and bind all selects
const controllers = create();

// Or bind a specific element
const root = document.querySelector('[data-slot="select"]');
const controller = createSelect(root, {
  defaultValue: 'apple',
  onValueChange: (value) => console.log('Selected:', value),
});

// Programmatic control
controller.open();
controller.close();
controller.select('banana');
console.log(controller.value); // 'banana'

// Cleanup
controller.destroy();

createSelect(root) is idempotent per root. Calling it again for the same element returns the existing controller; destroy it first if you need to rebind with different options.

API

Initialization

create(scope?)

Find and bind uninitialized [data-slot="select"] descendants of scope (defaults to document). Returns SelectController[] for newly bound roots. To initialize the scope element itself, use createSelect.

import { create } from "@data-slot/select";

const controllers = create();

createSelect(root, options?)

Create a SelectController for one root element. JavaScript options take precedence over the corresponding data attributes. Calling this again for a bound root returns its existing controller; destroy it before rebinding with new options.

import { createSelect } from "@data-slot/select";

const controller = createSelect(element, {});

Slots

Runtime Slots

  • select - Root container.
  • select-trigger - Required button that opens the popup and anchors its position.
  • select-value - Optional text target inside the trigger; displays the selected label or placeholder.
  • select-content - Required popup container for options.
  • select-viewport - Optional scroll container inside select-content; used for item-aligned scrolling when present.
  • select-item - Individual selectable option.
  • select-item-text - Optional text anchor inside select-item; preferred for exact item-aligned parity with Base/shadcn styles.
  • select-group - Groups related items.
  • select-label - Group label (inside a select-group).
  • select-positioner - Optional authored positioning wrapper (reused instead of generated wrapper).
  • select-portal - Optional authored portal wrapper that can contain select-positioner.

Style-only Slots

  • select-separator - Visual divider between items/groups.

Item labels resolve from authored data-label, then select-item-text, then the item's text content. data-label is an input attribute, not generated state.

Composed Portal Markup (Optional)

<div data-slot="select">
  <button data-slot="select-trigger">
    <span data-slot="select-value"></span>
  </button>
  <div data-slot="select-portal">
    <div data-slot="select-positioner">
      <div data-slot="select-content" hidden>...</div>
    </div>
  </div>
</div>

Native Label Support

Use a standard HTML <label for="..."> element to label the select. The for attribute should match the id on the trigger button. Clicking the label opens the select, and aria-labelledby is set automatically.

<label for="fruit-select">Choose a fruit</label>
<div data-slot="select">
  <button data-slot="select-trigger" id="fruit-select">
    <span data-slot="select-value"></span>
  </button>
  <div data-slot="select-content" hidden>
    <div data-slot="select-group">
      <div data-slot="select-label">Fruits</div>          <!-- group label -->
      <div data-slot="select-item" data-value="apple">Apple</div>
    </div>
  </div>
</div>

Data Attributes

The component sets these attributes to reflect state:

AttributeElementValuesDescription
data-stateroot, trigger, content"open" | "closed"Open state
data-positioncontent, viewport"item-aligned" | "popper"Resolved positioning mode authored by the controller
data-align-triggercontent"true" | "false"Whether the current mode aligns the selected item to the trigger
data-valuerootstringCurrent selected value
data-selecteditem(presence)Selected item
data-highlighteditem(presence)Focused/highlighted item
data-placeholdertrigger(presence)When showing placeholder

Options

Options can be passed via JavaScript or data attributes (JS takes precedence). Placement attributes (position, side, align, sideOffset, alignOffset, avoidCollisions, collisionPadding) resolve in this order:

  1. JavaScript option
  2. select-content
  3. select-positioner
  4. select root (fallback)
OptionData AttributeTypeDefaultDescription
defaultValuedata-default-valuestringnullInitial selected value
defaultOpendata-default-openbooleanfalseInitial popup open state
mountStrategyRoot data-mount-strategy"lazy" | "eager""lazy"Detach closed content, or keep it connected and hidden
placeholderdata-placeholderstring""Text when no value selected
disableddata-disabledbooleanfalseDisable interaction
requireddata-requiredbooleanfalseForm validation required
namedata-namestring-Form field name (creates an internal form control)
positiondata-position"item-aligned" | "popper""item-aligned"Positioning mode (see below)
avoidCollisionsdata-avoid-collisionsbooleantrueAdjust to stay in viewport
collisionPaddingdata-collision-paddingnumber8Viewport edge padding (px)
lockScrolldata-lock-scrollbooleantrueLock page scroll while the popup is open
highlightItemOnHoverdata-highlight-item-on-hoverbooleantrueHighlight and focus items on pointer hover

Positioning Modes

item-aligned (default): The popup positions itself so the selected item aligns with the trigger, similar to native <select> elements. The popup width matches the trigger width.

For the closest Base/shadcn visual parity, wrap the visible label inside each item with data-slot="select-item-text". When absent, the controller falls back to the whole select-item box for alignment, trigger display, and typeahead.

popper: The popup appears below or above the trigger like a dropdown menu. Additional options apply:

OptionData AttributeTypeDefaultDescription
sidedata-side"top" | "bottom""bottom"Popup placement
aligndata-align"start" | "center" | "end""start"Popup alignment
sideOffsetdata-side-offsetnumber4Distance from trigger (px)
alignOffsetdata-align-offsetnumber0Offset from alignment edge (px)

Both positioning modes set --transform-origin on the positioned element (select-positioner, or select-content when no positioner is used), so content animations can use transform-origin: var(--transform-origin, center).

The controller also mirrors the resolved positioning mode onto the DOM for styling:

  • data-position="item-aligned" | "popper" on select-content
  • data-position="item-aligned" | "popper" on select-viewport when present
  • data-align-trigger="true" | "false" on select-content

Consumers can style against these attributes directly and do not need to author them manually.

Callbacks

CallbackTypeDescription
onValueChange(value: string | null) => voidCalled when selection changes
onOpenChange(open: boolean) => voidCalled when popup opens/closes

Content mounting and server rendering

By default, Select removes its closed dropdown from the page’s DOM. This keeps pages with many selects smaller after initialization. The select button and selected value remain visible, and forms continue to work normally.

Opening the dropdown puts the same options back into the page. Their state and event listeners are preserved. Closing waits for any exit animation to finish, except when choosing an option, which closes the dropdown immediately.

Most applications can use this default without any changes.

If your code needs to find or update options while the dropdown is closed—for example, using querySelector—use eager mode to keep them in the DOM:

createSelect(root, { mountStrategy: "eager" });

You can also add data-mount-strategy="eager" to the Select root. A JavaScript option takes precedence over the HTML attribute.

With the default lazy mode, DOM queries won’t find closed options. You can still use the Select controller to change the selected value while closed; the displayed label and form value will update as usual.

Server rendering and pages without JavaScript

Lazy mounting does not reduce the HTML sent to the browser. Options are still included in your HTML; Select removes them from the DOM after JavaScript initializes.

Keep the dropdown’s initial markup hidden to prevent it briefly appearing before initialization. If the form must work without JavaScript, provide a native <select> fallback. Neither lazy nor eager mode provides that fallback automatically.

Controller

interface SelectController {
  readonly value: string | null;   // Current selected value
  readonly isOpen: boolean;        // Current open state
  select(value: string): void;     // Select a value
  open(): void;                    // Open the popup
  close(): void;                   // Close the popup
  destroy(): void;                 // Cleanup
}

Controller Destruction

destroy() permanently disposes the controller and hides any open surface without emitting an additional change event. Repeated destruction is safe; methods on the old controller become no-ops. Create a new controller on the same root to rebind it.

Focus restoration already queued by a close survives destruction. Closing with Tab still skips focus restoration to preserve normal Tab navigation.

Events

Outbound Events

root.addEventListener('select:change', (e) => {
  console.log('Value changed:', e.detail.value);
});

root.addEventListener('select:open-change', (e) => {
  console.log('Open state:', e.detail.open);
});

Inbound Events

select:set accepts { value?: string | null, open?: boolean }. Use value: null to clear the selection. When both fields are supplied, the value is applied before the open state. Programmatic selection works while disabled, but opening is blocked.

// Set value
root.dispatchEvent(new CustomEvent('select:set', {
  detail: { value: 'apple' }
}));

// Set open state
root.dispatchEvent(new CustomEvent('select:set', {
  detail: { open: true }
}));

Keyboard Navigation

KeyAction
Enter, Space, ArrowDown, ArrowUpOpen popup (when trigger focused)
ArrowDownMove to next item
ArrowUpMove to previous item
HomeMove to first item
EndMove to last item
Enter, SpaceSelect highlighted item
EscapeClose popup
TabClose popup and move focus
Type charactersJump to matching item

Accessibility

  • Trigger: role="combobox", aria-haspopup="listbox", aria-expanded, and aria-controls while open
  • Content: role="listbox", aria-labelledby
  • Item: role="option", aria-selected, aria-disabled
  • Group: role="group", aria-labelledby
  • Disabled items are skipped during keyboard navigation

Form Integration

When name is provided, an internal control is automatically created for form submission and kept out of the visual and keyboard flow:

<form>
  <div data-slot="select" data-name="fruit">
    <!-- ... -->
  </div>
  <button type="submit">Submit</button>
</form>

With required / data-required, this control participates in native validation. An empty required select blocks form submission and focuses the visible trigger. Disabled selects are excluded from validation and submission. Selected values are preserved exactly, including line breaks.

Resetting the form restores defaultValue and its displayed selection without emitting a value-change event, including when the select has no name. Synchronization happens on the next event-loop task, after the browser resets native controls. Calling preventDefault() on the reset event preserves the current state.

License

MIT

版本与发布记录

@data-slot/select 共发布 147 个版本,首次发布于 2026/02/04;过去 12 个月发布了 147 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
1.1.3latest2026/11/056 天前
1.1.22026/10/1428 天前
1.1.12026/10/051 个月前
1.1.02026/10/021 个月前
1.0.22026/09/271 个月前
1.0.12026/09/261 个月前

关于 @data-slot/select 的常见问题

@data-slot/select 是什么?

A headless, accessible select component for choosing a single value from a dropdown list.

如何安装 @data-slot/select?

在项目目录运行 npm install @data-slot/select,或使用 pnpm add / yarn add / bun add。

@data-slot/select 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@data-slot/select 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@data-slot/select 可以商用吗?

@data-slot/select 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@data-slot/select 的下载量有多少?

根据 npm 官方下载统计,@data-slot/select 在 2026/10/12 – 2026/11/10 这 30 天内被下载 6,049 次,日均约 202 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@data-slot/select 还在维护吗?

最新版本 1.1.3 发布于 2026/11/05(6 天前);至今共发布 147 个版本,其中过去 12 个月发布了 147 个;首次发布于 2026/02/04。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。