输入类

选择器

用户可以通过 Select 选择器从一个选项集合中去选中一个或多个选项,并呈现最终选择结果

代码演示

如何引入

<script lang="ts">
    import { Select } from '@fibrae/semi-ui-svelte';
</script>

Svelte 版没有 Select.Option 与 Select.OptGroup:子组件的数据在服务端首帧和键盘导航、过滤、全选里都读不到,选项只来自 optionList,分组写在条目的 group 字段上。

基本使用

选项写在 optionList 里,每个条目必须声明 value,label 是选项的文本。单向传入 value="douyin" 只作初值,要读写选中值用 bind:value





代码
<script lang="ts">
    import { Select } from '@fibrae/semi-ui-svelte';

    const optionList = [
        { value: 'douyin', label: '抖音' },
        { value: 'ulikecam', label: '轻颜相机' },
        { value: 'jianying', label: '剪映', disabled: true },
        { value: 'xigua', label: '西瓜视频' },
    ];
</script>

<Select aria-label="业务线" {optionList} style="width: 120px" value="douyin" />
<br />
<br />
<Select aria-label="业务线" disabled optionList={optionList.filter((option) => !option.disabled)} style="width: 120px" value="douyin" />
<br />
<br />
<Select aria-label="业务线" {optionList} placeholder="请选择业务线" style="width: 120px" />

以数组形式传入 Option

可以直接通过optionList传入一个对象数组,每个对象必须包含 value/label 属性(当然其他属性也可以通过此方式传入)

label 只接受字符串或数字;带标记的选项文字用 optionLabel snippet,见下文「自定义候选项渲染」。

代码
<script lang="ts">
    import { Select } from '@fibrae/semi-ui-svelte';

    const list = [
        { value: 'douyin', label: '抖音', otherKey: 0 },
        { value: 'ulikecam', label: '轻颜相机', disabled: true, otherKey: 1 },
        { value: 'jianying', label: '剪映', otherKey: 2 },
        { value: 'toutiao', label: '今日头条', otherKey: 3 },
    ];
</script>

<Select aria-label="业务线" optionList={list} placeholder="请选择业务线" style="width: 180px" />

多选

自 v2.28后,select 的选择器会自带 maxHeight 270,内容超出后可以通过垂直滚动查看。

配置multiple属性,可以支持多选

配置 maxTagCount 可以限制已选项展示的数量,超出部分将以+N 的方式展示

配置 ellipsisTrigger (>= v2.28.0) 对溢出部分的 tag 做自适应处理,当宽度不足时,最后一个tag内容作截断处理。开启该功能后会有一定性能损耗,不推荐在大表单场景下使用

配置 expandRestTagsOnClick (>= v2.28.0) 可以在设置 maxTagCount 情况下通过点击展示全剩余的tag

使用 showRestTagsPopover (>= v2.22.0) 可以设置在超出 maxTagCount 后,hover +N 是否显示 Popover,默认为 false。并且,还可以在 restTagsPopoverProps 属性中配置 Popover。

配置 max 属性可限制最大可选的数量,超出最大限制数量后无法选中,同时会触发 onExceed 回调







代码
<script lang="ts">
    import { Select, Toast } from '@fibrae/semi-ui-svelte';

    const optionList = [
        { value: 'douyin', label: '抖音' },
        { value: 'ulikecam', label: '轻颜相机' },
        { value: 'jianying', label: '剪映' },
        { value: 'xigua', label: '西瓜视频' },
    ];
    const onExceed = () => Toast.warning('最多只允许选择两项');
</script>

<Select aria-label="Select 示例" multiple {optionList} style="width: 320px" value={['douyin', 'ulikecam']} />
<br />
<br />
<Select aria-label="Select 示例" maxTagCount={2} multiple {optionList} restTagsPopoverProps={{ position: 'top' }} showRestTagsPopover style="width: 320px" value={['douyin', 'ulikecam', 'jianying']} />
<br />
<br />
<Select aria-label="Select 示例" max={2} multiple {onExceed} {optionList} style="width: 320px" value={['douyin']} />
<br />
<br />
<Select aria-label="Select 示例" ellipsisTrigger expandRestTagsOnClick maxTagCount={2} multiple {optionList} restTagsPopoverProps={{ position: 'top' }} showRestTagsPopover style="width: 220px" value={['xigua', 'ulikecam', 'jianying', 'douyin']} />

分组

在 optionList 的条目上写 group: { key, label } 分组:同一组的条目必须相邻,key 相同的相邻条目归为一组,label 是分组标题,没有 label 的分组不渲染标题。分组渲染为 role="group",以标题为名称。搜索时没有可见选项的分组整组隐藏,搜索词命中分组标题时显示该组全部选项。用 groupLabel snippet 定制标题内容,参数为 { group },不传时显示 group.label。开启 virtualize 时不渲染分组标题与 role="group",选项按顺序平铺

代码
<script lang="ts">
    import { Select } from '@fibrae/semi-ui-svelte';

    const asia = { key: 'asia', label: 'Asia' };
    const europe = { key: 'europe', label: 'Europe' };
    const southAmerica = { key: 'south-america', label: 'South America' };

    const optionList = [
        { value: 'a-1', label: 'China', group: asia },
        { value: 'a-2', label: 'Korea', group: asia },
        { value: 'b-1', label: 'Germany', group: europe },
        { value: 'b-2', label: 'France', group: europe },
        { value: 'c-1', label: 'Peru', group: southAmerica },
    ];
</script>

<Select aria-label="地区" filter {optionList} placeholder="" style="width: 180px" />
代码
<script lang="ts">
    import { Select } from '@fibrae/semi-ui-svelte';

    const data = [
        {
            label: 'Asia',
            children: [
                { value: 'a-1', label: 'China' },
                { value: 'a-2', label: 'Korea' },
            ],
        },
        {
            label: 'Europe',
            children: [
                { value: 'b-1', label: 'Germany' },
                { value: 'b-2', label: 'France' },
            ],
        },
        {
            label: 'South America',
            children: [{ value: 'c-1', label: 'Peru' }],
        },
    ];

    const optionList = data.flatMap(({ label, children }) => children.map((option) => ({ ...option, group: { key: label, label } })));
</script>

<Select aria-label="地区" filter {optionList} placeholder="" style="width: 180px">
    {#snippet groupLabel({ group })}
        <strong>{group.label}</strong>
    {/snippet}
</Select>

不同尺寸

通过 Size 控制选择器的大小尺寸: small / default / large





代码
<script lang="ts">
    import { Select } from '@fibrae/semi-ui-svelte';

    const optionList = [{ value: 'ulikecam', label: '轻颜相机' }];
</script>

<Select aria-label="small" {optionList} placeholder="请选择业务线" size="small" style="width: 180px" />
<br />
<br />
<Select aria-label="default" {optionList} placeholder="请选择业务线" style="width: 180px" />
<br />
<br />
<Select aria-label="large" {optionList} placeholder="请选择业务线" size="large" style="width: 180px" />

不同校验状态样式

validateStatus: default / warning / error
仅影响背景颜色等样式表现





代码
<script lang="ts">
    import { Select } from '@fibrae/semi-ui-svelte';

    const optionList = [{ value: 'ulikecam', label: '轻颜相机' }];
</script>

<Select aria-label="default" {optionList} style="width: 180px" />
<br />
<br />
<Select aria-label="warning" {optionList} style="width: 180px" validateStatus="warning" />
<br />
<br />
<Select aria-label="error" {optionList} style="width: 180px" validateStatus="error" />

配置前缀、后缀、清除按钮

  • 可以通过 prefix snippet 传入选择框前缀,通过 suffix snippet 传入选择框后缀,可以为文本或者节点
    当 snippet 内容为文本或者 Icon 时,会自动带上左右间隔,若为自定义节点,则左右间隔为 0
  • 通过showClear控制清除按钮是否展示
  • 通过showArrow控制右侧下拉箭头是否展示


代码
<script lang="ts">
    import { IconGift, IconVigoLogo } from '@fibrae/semi-icons-svelte';
    import { Select } from '@fibrae/semi-ui-svelte';

    const optionList = [
        { value: 'douyin', label: '抖音' },
        { value: 'ulikecam', label: '轻颜相机' },
        { value: 'jianying', label: '剪映' },
        { value: 'xigua', label: '西瓜视频' },
    ];
</script>

<Select aria-label="Select 示例" {optionList} showClear style="width: 320px" value="ulikecam">
    {#snippet prefix()}
        <IconVigoLogo />
    {/snippet}
</Select>
<br />
<br />
<Select aria-label="Select 示例" {optionList} showArrow={false} style="width: 320px" value="ulikecam">
    {#snippet prefix()}
        <IconVigoLogo />
    {/snippet}
    {#snippet suffix()}
        <IconGift />
    {/snippet}
</Select>

在顶部/底部渲染附加项

我们在弹出层顶部、底部分别预留了插槽,当你需要在弹出层中添加自定义 node 时
可以通过innerBottomSlot或者outerBottomSlot传入,自定义 node 将会被渲染在弹出层底部;可以通过innerTopSlot或者outerTopSlot传入,自定义 node 将会被渲染在弹出层顶部。

在 Svelte 中它们是同名的 snippet,写作 {#snippet innerBottomSlot()}...{/snippet},其余三个同理。

  • innerTopSlot 和 innerBottomSlot将会被渲染在 optionList 内部,当滚动到 optionList 顶部/底部时展现
  • outerTopSlot 和 outerBottomSlot将会被渲染为与 optionList 平级,无论 optionList 是否滚动,都会始终展现

outerBottomSlot:

innerBottomSlot:

代码
<script lang="ts">
    import { Select } from '@fibrae/semi-ui-svelte';

    const optionList = [
        { value: 'douyin', label: '抖音' },
        { value: 'ulikecam', label: '轻颜相机' },
        { value: 'jianying', label: '剪映' },
        { value: 'duoshan', label: '多闪' },
        { value: 'xigua', label: '西瓜视频' },
    ];
    const innerSlotStyle = 'background-color: var(--color-white); height: 36px; display: flex; align-items: center; cursor: pointer; padding-left: 32px; border-top: 1px solid var(--semi-color-border); border-radius: 0 0 6px 6px; color: var(--semi-color-link)';
    const outSlotStyle = 'background-color: var(--semi-color-fill-0); height: 36px; display: flex; padding-left: 32px; color: var(--semi-color-link); align-items: center; cursor: pointer; border-top: 1px solid var(--semi-color-border); border-radius: 0 0 6px 6px';
</script>

<div>
    <p>outerBottomSlot:</p>
    <Select aria-label="outerBottomSlot" autoAdjustOverflow={false} defaultOpen dropdownStyle="width: 180px" maxHeight={150} {optionList} placeholder="自定义外侧底部slot,始终显示" position="bottom" style="width: 300px">
        {#snippet outerBottomSlot()}
            <div style={outSlotStyle}>
                <span style="color: var(--semi-color-link)">未找到应用?</span>
            </div>
        {/snippet}
    </Select>
    <p style="margin-top: 200px">innerBottomSlot:</p>
    <Select aria-label="innerBottomSlot" dropdownStyle="width: 180px" maxHeight={150} {optionList} placeholder="自定义内侧底部slot,滚动至底部显示" style="width: 300px">
        {#snippet innerBottomSlot()}
            <div style={innerSlotStyle}>点击加载更多</div>
        {/snippet}
    </Select>
</div>

通过 outerTopSlot 将内容插入顶部插槽

代码
<script lang="ts">
    import { RadioGroup, Select, type RadioChangeEvent, type SelectValue } from '@fibrae/semi-ui-svelte';

    interface Item {
        value: string;
        label: string;
    }

    const list: Record<string, Item[]> = {
        component: [
            { value: 'select', label: '选择器' },
            { value: 'tabs', label: '标签' },
            { value: 'avatar', label: '头像' },
            { value: 'button', label: '按钮' },
        ],
        design: [
            { value: 'color', label: '颜色' },
            { value: 'dark', label: '暗色模式' },
            { value: 'icon', label: '图标' },
            { value: 'font', label: '字体' },
        ],
        feedback: [
            { value: 'faq', label: '常见问题' },
            { value: 'join', label: '加入用户群' },
            { value: 'hornbill', label: '犀鸟反馈问题' },
        ],
    };
    const categoryOptions = [
        { value: 'component', label: '组件' },
        { value: 'design', label: '设计' },
        { value: 'feedback', label: '反馈' },
    ];

    let key = $state('component');
    let value = $state<SelectValue>({ value: 'faq', label: '常见问题' });

    const changeCategory = (event: RadioChangeEvent) => {
        key = String(event.target.value);
    };
</script>

<Select aria-label="选项" autoAdjustOverflow={false} bind:value defaultOpen onChangeWithObject optionList={list[key]} style="width: 200px">
    {#snippet outerTopSlot()}
        <!-- The radio group switches with arrow keys, so categories need no tabpanel association -->
        <div style="padding: 8px 12px; border-bottom: 0.5px solid var(--semi-color-border)">
            <RadioGroup aria-label="选项分类" buttonSize="small" onChange={changeCategory} options={categoryOptions} type="button" value={key} />
        </div>
    {/snippet}
</Select>

受控组件

用 bind:value={x} 双向同步所选中的值;bind:value={() => x, (next) => { ... }} 函数绑定下 Select 完全受控,setter 可以拒绝或改写。单向 value={x} 只作初值。不提供 defaultValue。

代码
<script lang="ts">
    import { Select } from '@fibrae/semi-ui-svelte';

    const optionList = [
        { value: 'douyin', label: '抖音' },
        { value: 'ulikecam', label: '轻颜相机' },
        { value: 'jianying', label: '剪映' },
        { value: 'xigua', label: '西瓜视频' },
    ];

    let value = $state<string | undefined>('xigua');
</script>

<Select aria-label="业务线" bind:value {optionList} placeholder="受控的Select" style="width: 300px" />

动态修改 Options

如果需要动态更新 Options,应该使用 bind:value,或在 onChange 里把值写回



代码
<script lang="ts">
    import { Button, Select } from '@fibrae/semi-ui-svelte';

    let options = $state([1, 2, 3, 4]);

    const optionList = $derived(options.map((option) => ({ value: option, label: String(option) })));

    const add = () => {
        const length = Math.ceil(Math.random() * 10);
        options = Array.from({ length }, (_, i) => i + 1);
    };
</script>

<Select aria-label="数字" {optionList} placeholder="请选择" style="width: 180px" value={4} />
<br />
<br />
<Button onclick={add}>changeOptions Dynamic</Button>

联动

用 bind:value 或在 onChange 里写回,实现不同 Select 之间的联动。如果是带有层级关系的复杂联动建议直接使用Cascader组件

代码
<script lang="ts">
    import { Select, type SelectValue } from '@fibrae/semi-ui-svelte';

    const provinces = ['四川', '广东'];
    const maps: Record<string, string[]> = {
        四川: ['成都', '都江堰'],
        广东: ['广州', '深圳', '东莞'],
    };

    let province = $state(provinces[0]);
    let city = $state<string | undefined>(maps[provinces[0]][0]);

    const provinceList = provinces.map((item) => ({ value: item, label: item }));
    const cityList = $derived(maps[province].map((item) => ({ value: item, label: item })));

    const changeProvince = (next: SelectValue) => {
        if (typeof next !== 'string') {
            return;
        }
        province = next;
        city = maps[next][0];
    };
</script>

<Select aria-label="省份" onChange={changeProvince} optionList={provinceList} style="width: 150px; margin: 10px" value={province} />
<Select aria-label="城市" bind:value={city} optionList={cityList} style="width: 150px; margin: 10px" />

开启搜索

将 filter 置为 true,开启搜索能力。默认搜索策略将为 input 输入值与 option 的 label 值进行 include 对比
默认情况下,多选选中后会自动清空搜索关键字。若你希望保留,可以通过 autoClearSearchValue 设为 false 关闭默认行为(v2.3 后提供)

搜索框位置

默认搜索框展示于 Select 的 Trigger 触发器上。通过 searchPosition 可以指定不同的位置,可选 dropdown、trigger。 在 v2.61.0后提供若希望定制位于 dropdown 中的 Input 搜索框的 placeholder,可以通过 searchPlaceholder 控制
若 searchPosition 值为 trigger,当showClear=true 时,点击Trigger区域的清空按钮,将同时清空已选项以及搜索框中的文本
若 searchPosition 值为 dropdown,当showClear=true 时,点击Trigger区域清空按钮,仅清空已选项。点击搜索框中的清空按钮,仅清空搜索文本



代码
<script lang="ts">
    import { Select } from '@fibrae/semi-ui-svelte';

    const businessList = [
        { value: 'douyin', label: '抖音' },
        { value: 'ulikecam', label: '轻颜相机' },
        { value: 'jianying', label: '剪映' },
        { value: 'xigua', label: '西瓜视频' },
    ];
    const semiList = Array.from({ length: 5 }, (_, i) => ({ value: `semi-${i}`, label: `Semi-${i}` }));
</script>

<Select aria-label="单选" filter optionList={businessList} placeholder="我的搜索框在下拉菜单中" searchPlaceholder="带搜索功能的单选" searchPosition="dropdown" style="width: 200px" value="ulikecam" />
<br />
<br />
<Select aria-label="多选" autoClearSearchValue={false} filter multiple optionList={semiList} placeholder="我的搜索框在下拉菜单中" searchPlaceholder="带搜索功能的多选" searchPosition="dropdown" style="width: 300px" value={['semi-1']} />

远程搜索

带有远程搜索,防抖请求,加载状态的多选示例
通过filter开启搜索能力
将remote设置为 true 关闭对当前数据的筛选过滤通过动态更新optionList更新下拉菜单中的备选项

使用 bind:value,通过 onSearch 获取搜索内容;传 emptyContent={null} 隐藏空状态

自定义搜索逻辑

可以将 filter 置为自定义函数,定制你想要的搜索策略
如下例子,选项 label 值都是大写,默认的检索策略是字符串 include 对比,会区分大小写。
通过传入自定义 filter 函数,检索时输入小写字母也能搜到相应内容。

代码
<script lang="ts">
    import { Select, type SelectOptionProps } from '@fibrae/semi-ui-svelte';

    const optionList = [
        { value: 'douyin', label: 'douyin' },
        { value: 'ulikecam', label: 'HOTSOON' },
        { value: 'jianying', label: 'PIPIXIA' },
        { value: 'xigua', label: 'XIGUA' },
    ];

    const searchLabel = (sugInput: string, option: SelectOptionProps) => {
        const label = String(option.label).toUpperCase();
        const sug = sugInput.toUpperCase();
        return label.includes(sug);
    };
</script>

<Select aria-label="业务线" filter={searchLabel} {optionList} placeholder="try douyin" style="width: 180px" />

自定义已选项标签渲染

默认情况下,选中选项后会将选项的 label 回填到选择框中
但你可以通过 snippet 自定义选择框中已选项的渲染结构,参数为 { option, index, disabled, onClose }

  • selectedItem:单选时替换选择框中显示的内容;多选时只替换内置标签里的内容,标签仍带有背景色以及关闭按钮
  • tag:多选时替换整个标签,同时提供时优先于 selectedItem
  • 调用 onClose 移除该选项,单选时清空选中值
  • 写在 optionList 条目上的其他字段(如示例中的 email、avatar)会随 option 一起传入
代码
<script lang="ts">
    import { Avatar, Select, Tag, type SelectOptionProps, type SelectValue } from '@fibrae/semi-ui-svelte';

    const optionStyle = 'display: flex; padding-left: 24px; padding-top: 10px; padding-bottom: 10px';

    const list = [
        {
            name: '夏可漫',
            email: 'xiakeman@example.com',
            avatar: '/assets/placeholder/avatar-a.svg',
        },
        {
            name: '申悦',
            email: 'shenyue@example.com',
            avatar: '/assets/root-web-sites/bag.jpeg',
        },
        {
            name: '曲晨一',
            email: 'quchenyi@example.com',
            avatar: '/assets/placeholder/avatar-c.svg',
        },
        {
            name: '文嘉茂',
            email: 'wenjiamao@example.com',
            avatar: '/assets/root-web-sites/6fbafc2d-e3e6-4cff-a1e2-17709c680624.png',
        },
    ].map((item) => ({ ...item, value: item.name, label: item.name, showTick: true, style: optionStyle }));

    const onChange = (value: SelectValue) => console.log(value);
</script>

{#snippet optionLabel({ option }: { option: SelectOptionProps })}
    <Avatar alt="" size="small" src={option.avatar} />
    <div style="margin-left: 8px">
        <div style="font-size: 14px">{option.name}</div>
        <div style="color: var(--color-text-2); font-size: 12px; line-height: 16px; font-weight: normal">
            {option.email}
        </div>
    </div>
{/snippet}

<Select aria-label="单选" {onChange} {optionLabel} optionList={list} placeholder="请选择" style="width: 280px; height: 40px" value="申悦">
    {#snippet selectedItem({ option })}
        <div style="display: flex; align-items: center">
            <Avatar alt="" size="small" src={option.avatar} />
            <span style="margin-left: 8px">{option.email}</span>
        </div>
    {/snippet}
</Select>
<Select aria-label="多选圆形头像" maxTagCount={2} multiple {onChange} {optionLabel} optionList={list} placeholder="请选择" style="width: 280px; margin-top: 20px" value={['申悦', '曲晨一']}>
    {#snippet tag({ option, onClose })}
        <Tag avatarShape="circle" avatarSrc={option.avatar} closable {onClose} size="large">
            {option.name}
        </Tag>
    {/snippet}
</Select>
<Select aria-label="多选方形头像" maxTagCount={2} multiple {onChange} {optionLabel} optionList={list} placeholder="请选择" style="width: 280px; margin-top: 20px" value={['申悦', '曲晨一']}>
    {#snippet tag({ option, onClose })}
        <Tag avatarShape="square" avatarSrc={option.avatar} closable {onClose} size="large">
            {option.name}
        </Tag>
    {/snippet}
</Select>

自定义弹出层样式

你可以通过 dropdownClassName、dropdownStyle 控制弹出层的样式
例如当自定义弹出层的宽度时,可以通过 dropdownStyle 传入 width

代码
<script lang="ts">
    import { Select } from '@fibrae/semi-ui-svelte';

    const optionList = [
        { value: 'douyin', label: '抖音' },
        { value: 'ulikecam', label: '轻颜相机' },
        { value: 'jianying', label: '剪映' },
        { value: 'xigua', label: '西瓜视频' },
    ];
</script>

<Select aria-label="业务线" dropdownClassName="test" dropdownStyle="width: 250px" {optionList} placeholder="自定义弹出层样式的" style="width: 180px" />

获取选项的其他属性

默认情况下onChange只能拿到 value,如果需要拿选中节点的其他属性,可以使用onChangeWithObject属性
此时onChange函数的入参将会是 object,包含 option 的各种属性,例如 onChange({ value, label, ...rest })

onChange回调:

onChange回调:

代码
<script lang="ts">
    import { Select, TextArea, type SelectValue } from '@fibrae/semi-ui-svelte';

    interface Item {
        value: string;
        label: string;
        type: number;
    }

    const list: Item[] = [
        { value: 'douyin', label: '抖音', type: 1 },
        { value: 'ulikecam', label: '轻颜相机', type: 2 },
        { value: 'jianying', label: '剪映', type: 3 },
        { value: 'toutiao', label: '今日头条', type: 4 },
    ];

    let cbValue = $state<SelectValue>();
    let multipleCbValue = $state<SelectValue>();

    const onChange = (value: SelectValue) => {
        cbValue = value;
        console.log(value);
    };

    const onMultipleChange = (value: SelectValue) => {
        multipleCbValue = value;
        console.log(value);
    };
</script>

<div>
    <div>
        <Select aria-label="单选" {onChange} onChangeWithObject optionList={list} placeholder="单选" style="width: 150px" value={{ ...list[0] }} />
        <h4 id="select-on-change-with-object-single">onChange回调:</h4>
        <TextArea aria-labelledby="select-on-change-with-object-single" autosize rows={2} style="width: 320px; margin-bottom: 48px" value={JSON.stringify(cbValue)} />
    </div>
    <div>
        <Select aria-label="多选" multiple onChange={onMultipleChange} onChangeWithObject optionList={list} placeholder="多选" style="width: 320px" value={[]} />
        <h4 id="select-on-change-with-object-multiple">onChange回调:</h4>
        <TextArea aria-labelledby="select-on-change-with-object-multiple" autosize style="width: 320px" value={JSON.stringify(multipleCbValue)} />
    </div>
</div>

创建条目

设置allowCreate,可以创建并选中选项中不存在的条目

允许通过 createItem snippet 自定义创建标签时的内容显示(注意你需要自定义样式,与虚拟化结合使用时必须把 style 用在自定义元素上),参数为 { inputValue, focus, style },不提供时显示语言包中的「创建」加输入内容。创建选项时触发 onCreate

可以配合defaultActiveFirstOption属性使用,自动选中第一项,当输入完内容直接回车时,可立即创建



With createItem
代码
<script lang="ts">
    import { Select } from '@fibrae/semi-ui-svelte';

    const optionList = [
        { value: 'douyin', label: '抖音' },
        { value: 'ulikecam', label: '轻颜相机' },
        { value: 'jianying', label: '剪映' },
        { value: 'toutiao', label: '今日头条' },
    ];
</script>

<Select allowCreate aria-label="业务线" defaultActiveFirstOption filter multiple onChange={(value) => console.log(value)} {optionList} style="width: 400px" />
<br />
<br />
<Select allowCreate aria-label="业务线" defaultActiveFirstOption filter multiple onChange={(value) => console.log(value)} {optionList} placeholder="With createItem" style="width: 400px">
    {#snippet createItem({ inputValue, style })}
        <div style={`padding: 10px; ${style ?? ''}`}>Create Item:{inputValue}</div>
    {/snippet}
</Select>

虚拟化

传入virtualize时开启列表虚拟化,用于大量 Option 节点的情况优化性能
virtualize 是一个包含下列值的对象:

  • height: Option 列表高度值,默认 270 (v2.20.8 前为 300)
  • width: Option 列表宽度值,默认 100%
  • itemSize: 每行 Option 的高度,必传
代码
<script lang="ts">
    import { Select } from '@fibrae/semi-ui-svelte';

    const options = Array.from({ length: 3000 }, (_, i) => ({ label: `option-${i}`, value: i }));
    const virtualize = {
        height: 270,
        width: '100%',
        itemSize: 36,
    };
</script>

<Select aria-label="virtualize" filter optionList={options} placeholder="拥有3k个Option的Select" style="width: 260px" {virtualize} />

自定义触发器

如果 Select 默认的触发器样式满足不了你的需求,可以用 trigger snippet 自定义选择框的内容
如果想保留搜索筛选能力,又不希望自己渲染 Input 相关的结构,可以同时通过 searchPosition='dropdown',将默认的搜索框置于下拉列表中

trigger 的参数如下

interface SelectTriggerSnippetProps {
    value: SelectOptionProps[]; // 当前所有已选中的 option
    inputValue: string; // 当前搜索关键字
    placeholder?: string; // Select 的 placeholder
    disabled: boolean; // 是否禁用 Select
    onSearch: (inputValue: string) => void; // 更新搜索关键字,用于把自定义 Input 的值同步给 Select 内部。需同时设置 filter
    onClear: (event?: MouseEvent) => void; // 清空已选值。绑在触发器内的控件上时传入点击事件,避免这次点击重新打开下拉列表
    onRemove: (option: SelectOptionProps) => void; // 移除单个已选项,option 至少需带有 label、value
}

不同背景色的触发器



使用 circle Tag 作为触发器

代码
<script lang="ts">
    import { IconAppCenter, IconChevronDown } from '@fibrae/semi-icons-svelte';
    import { Select, Tag, type SelectValue } from '@fibrae/semi-ui-svelte';

    let valList = $state<SelectValue>(['douyin', 'ulikecam']);

    const list = [
        { value: 'douyin', label: '抖音' },
        { value: 'ulikecam', label: '轻颜相机' },
        { value: 'jianying', label: '剪映' },
        { value: 'toutiao', label: '今日头条' },
    ];
</script>

<div>
    <h4>不同背景色的触发器</h4>
    <Select aria-label="不同背景色的触发器" bind:value={valList} filter multiple optionList={list} searchPosition="dropdown" style="width: 240px">
        {#snippet trigger({ value })}
            <div style="min-width: 112px; background-color: var(--semi-color-primary-light-default); height: 32px; display: flex; align-items: center; padding-left: 12px; border-radius: 3px; color: var(--semi-color-primary)">
                <div style="font-weight: 600; flex-shrink: 0; font-size: 14px">业务线</div>
                <div style="margin: 4px; white-space: nowrap; text-overflow: ellipsis; flex-grow: 1; overflow: hidden">
                    {value.map((item) => item.label).join(' , ')}
                </div>
                <IconAppCenter style="margin-right: 8px; flex-shrink: 0" />
            </div>
        {/snippet}
    </Select>
    <br />
    <br />
    <h4>使用 circle Tag 作为触发器</h4>
    <Select aria-label="circle Tag 触发器" bind:value={valList} filter multiple optionList={list} searchPosition="dropdown" style="width: 240px; margin-top: 20px; outline: 0">
        {#snippet trigger({ value })}
            <div style="margin: 4px; white-space: nowrap; text-overflow: ellipsis; flex-grow: 1; overflow: hidden; display: flex; align-items: center">
                <Tag color="cyan" shape="circle" size="large">
                    {value.map((item) => item.label).join(' / ')}
                    {#snippet suffixIcon()}
                        <IconChevronDown />
                    {/snippet}
                </Tag>
            </div>
        {/snippet}
    </Select>
</div>

下例是更复杂的例子:复用了 TagInput 拖拽排序能力,通过自定义触发器为 Select 增加排序

可对已选项拖拽重新排序的 Select

代码
<script lang="ts">
    import { Select, TagInput, type SelectValue } from '@fibrae/semi-ui-svelte';

    let valList = $state<SelectValue>(['douyin', 'ulikecam']);
    let inputVal = $state('');

    const list = [
        { value: 'douyin', label: '抖音' },
        { value: 'ulikecam', label: '轻颜相机' },
        { value: 'jianying', label: '剪映' },
        { value: 'toutiao', label: '今日头条' },
    ];

    const handleSort = (currentLabels: string[]) => {
        valList = currentLabels.flatMap((item) => list.find((i) => i.label === item)?.value ?? []);
    };
</script>

<h4>可对已选项拖拽重新排序的 Select</h4>
<Select aria-label="可拖拽排序的 Select" bind:value={valList} filter multiple optionList={list} style="width: 240px">
    {#snippet trigger({ value, onSearch })}
        <div role="presentation" onkeydown={(event) => event.stopPropagation()}>
            <TagInput
                allowDuplicates={false}
                draggable
                inputValue={inputVal}
                onChange={handleSort}
                onInputChange={(word) => {
                    onSearch(word);
                    inputVal = word;
                }}
                showClear
                value={value.map((item) => String(item.label))}
            />
        </div>
    {/snippet}
</Select>

自定义候选项渲染

  • 简单的自定义:通过 optionLabel snippet 只替换选项行里的文字,参数为 { option }。选中图标、行的 role="option"、选中与禁用状态、点击和键盘行为都保持不变,内容会自动带上内边距、背景色等样式。选项的 label 仍用于搜索、回填触发器和可访问名称;optionLabel 里的内容不会高亮搜索关键字
  • 完全自定义:通过 optionItem snippet,你可以完全接管列表中候选项的渲染,并且从参数中,获取到相关的状态值。实现更高自由度的结构渲染
    参数为 { id, value, label, selected, focused, disabled, inputValue, class, style, onclick, onmouseenter },以及写在 optionList 条目上的其他字段,注意事项:
    1. 参数中的 style 需在 wrapper dom 上进行消费,否则在虚拟化场景下会无法正常使用
    2. 参数中的 class、onmouseenter 需在 wrapper dom 上进行消费,否则上下键盘操作时显示会有问题
    3. 选中(selected)、聚焦(focused)、禁用(disabled)等状态的样式需自行加上,你可以从参数中获取到相对的 boolean 值
    4. 点击选中需要把参数中的 onclick 绑定到 wrapper dom 上
    5. 参数中的 id 需与 role="option"、aria-selected、aria-disabled 一起写在 wrapper dom 上:Select 的 aria-activedescendant 指向该 id,读屏才能读出方向键移到的候选项;打开下拉或方向键移动时也按该 id 把候选项滚进列表可视区


多选
代码
<script lang="ts">
    import { Checkbox, Highlight, Select, type SelectOptionItemSnippetProps } from '@fibrae/semi-ui-svelte';

    let inputValue = $state('');

    const optionList = [
        { value: 'douyin', label: '抖音', otherKey: 0 },
        { value: 'ulikecam', label: '轻颜相机', disabled: true, otherKey: 1 },
        { value: 'jianying', label: '剪映', otherKey: 2 },
        { value: 'toutiao', label: '今日头条', otherKey: 3 },
    ];
</script>

<!--
    Put style on the outer DOM or the virtual list breaks; add selected/focused/disabled styles from the snippet
    params; bind onmouseenter and class on the outer DOM or arrow keys display wrongly; put id there so screen
    readers announce the option the arrow keys reach
-->
{#snippet optionItem({ id, disabled, selected, label, focused, class: className, style, onclick, onmouseenter }: SelectOptionItemSnippetProps)}
    <div
        aria-disabled={disabled}
        aria-selected={selected}
        class={[
            'custom-option-render',
            {
                'custom-option-render-focused': focused,
                'custom-option-render-disabled': disabled,
                'custom-option-render-selected': selected,
            },
            className,
        ]}
        {id}
        role="option"
        {style}
        {onclick}
        {onmouseenter}
    >
        <Checkbox checked={selected} />
        <div class="option-right">
            <Highlight searchWords={[inputValue]} sourceString={String(label)} />
        </div>
    </div>
{/snippet}

<Select aria-label="单选" dropdownClassName="components-select-demo-renderOptionItem" filter onSearch={(value) => (inputValue = value)} {optionItem} {optionList} placeholder="单选" style="width: 180px" />
<br />
<br />
<Select aria-label="多选" dropdownClassName="components-select-demo-renderOptionItem" filter multiple onSearch={(value) => (inputValue = value)} {optionItem} {optionList} placeholder="多选" style="width: 320px" />
.components-select-demo-renderOptionItem {
    .custom-option-render {
        display: flex;
        font-size: 14px;
        line-height: 20px;
        word-break: break-all;
        padding-left: 12px;
        padding-right: 12px;
        padding-top: 8px;
        padding-bottom: 8px;
        color: var(--semi-color-text-0);
        position: relative;
        display: flex;
        align-items: center;
        cursor: pointer;
        box-sizing: border-box;
        .option-right {
            margin-left: 8px;
            display: inline-flex;
            align-items: center;
        }
        &:active {
            background-color: var(--semi-color-fill-1);
        }
        &-focused {
            background-color: var(--semi-color-fill-0);
        }
        &-selected {
            //font-weight: 700;
        }
        &-disabled {
            color: var(--semi-color-disabled-text);
            cursor: not-allowed;
        }
        &:first-of-type {
            margin-top: 4px;
        }
        &:last-of-type {
            margin-bottom: 4px;
        }
    }
}

API 参考

Select Props

Props

属性说明类型默认值
allowCreate是否允许创建列表中不存在的选项,需配合 filter。booleanfalse
arrowIcon自定义下拉箭头,snippet。Snippet-
autoAdjustOverflow下拉层溢出视口时是否自动调整方位。booleantrue
autoClearSearchValue多选选中后是否自动清空搜索关键字。booleantrue
autofocus挂载后是否自动聚焦。booleanfalse
borderless是否无边框。booleanfalse
clearIcon自定义清除按钮图标,snippet。Snippet-
clickToHide多选时点击选项后是否关闭下拉列表。booleanfalse
createItem创建选项那一行的内容,snippet,参数为 { inputValue, focus, style };虚拟化时要把 style 用在自定义元素上。TypeSnippet<[SelectCreateItemSnippetProps]>-
defaultActiveFirstOption是否默认高亮第一个可用选项。booleantrue
defaultOpen挂载后是否展开下拉列表。Select 没有受控的展开状态。booleanfalse
disabled是否禁用。boolean-
dropdownClassName下拉层的类名。string-
dropdownMatchSelectWidth下拉层的最小宽度是否跟随触发器宽度。booleantrue
dropdownStyle下拉层的样式,字符串。string-
ellipsisTrigger是否对溢出的标签做自适应处理,宽度不足时最后一个标签内容截断。有一定性能损耗,不推荐在大表单场景使用。booleanfalse
emptyContent没有选项时的内容,snippet;传 null 隐藏空状态。Snippet | null-
expandRestTagsOnClick设置 maxTagCount 时,打开下拉列表后是否展开被折叠的标签。booleanfalse
filter是否开启搜索。传 true 时用输入值与选项 label 或分组标题做 include 对比(不区分大小写),传函数时自定义匹配。Typeboolean | ((inputValue: string, option: SelectOptionProps) => boolean)false
groupLabel替换分组标题的内容,snippet,参数为 { group }(含 key、label);不传时显示 group.label。TypeSnippet<[SelectGroupLabelSnippetProps]>-
id触发器的 id,选项的 id 由它派生。string-
innerBottomSlot渲染在选项列表内部底部的内容,snippet,滚动到底部时展现。Snippet-
innerTopSlot渲染在选项列表内部顶部的内容,snippet,滚动到顶部时展现。Snippet-
inputProps搜索框 Input 的额外属性,class 与 style 落在 Input 外层。SelectInputProps-
insetLabel内嵌标签,snippet。没有 prefix 时渲染,并作为 combobox 的名称来源。Snippet-
insetLabelId内嵌标签容器的 id,供 aria-labelledby 引用;未传时在渲染 insetLabel 时由组件生成。string-
loading是否加载中,加载中时下拉列表显示加载状态而不是选项。booleanfalse
max多选时最多可选的数量,超出时触发 onExceed。number-
maxHeight下拉列表的最大高度。string | number270
maxTagCount多选时标签的最大展示数量,超出后以 +N 形式展示。number-
motion是否开启下拉层的动画。booleantrue
multiple是否多选。booleanfalse
onBlur焦点离开 Select 时触发一次;点击打开的下拉层之外时传入其 mousedown 事件。Type(event: FocusEvent | MouseEvent) => void-
onChange选中值变化时的回调,入参为新的值(开启 onChangeWithObject 时为选项对象)。Type(value: SelectValue) => void-
onChangeWithObjectonChange 与 value 是否使用选项对象而不是选项的值。booleanfalse
onClear点击清除按钮时的回调。Type() => void-
onCreate创建选项时的回调。Type(option: SelectOptionProps) => void-
onDeselect多选时取消选中某个选项的回调。Type(value: string | number, option: SelectOptionProps) => void-
onDropdownVisibleChange下拉列表展开或收起时的回调。Type(visible: boolean) => void-
onExceed选中数量超过 max 时的回调。Type(option: SelectOptionProps) => void-
onFocus焦点进入 Select 时触发一次。Type(event: FocusEvent) => void-
onListScroll下拉列表滚动时的回调。Type(event: Event) => void-
onSearch搜索关键字变化时的回调;经 search() 或 trigger snippet 的 onSearch 触发时没有事件参数。Type(value: string, event?: Event) => void-
onSelect选中某个选项时的回调。Type(value: string | number, option: SelectOptionProps) => void-
optionItem替换整个选项行,snippet,参数含 id、value、label、selected、focused、disabled、inputValue、class、style、onclick、onmouseenter 以及条目上的其他字段。id 要与 role="option" 一起写在选项元素上。TypeSnippet<[SelectOptionItemSnippetProps]>-
optionLabel只替换选项行里的文字,snippet,参数为 { option }。选中图标、行的 role="option"、状态与键盘行为不变;label 仍用于搜索与可访问名称,内容里不高亮搜索关键字。TypeSnippet<[SelectOptionLabelSnippetProps]>-
optionList选项数据,条目含 value、label、disabled、showTick、class、style 以及可选的 group: { key, label },其他字段随选项记录回传。同一分组的条目必须相邻。SelectOptionProps[]-
outerBottomSlot下拉层底部与选项列表平级的内容,snippet,列表滚动时始终展现。Snippet-
outerTopSlot下拉层顶部与选项列表平级的内容,snippet,列表滚动时始终展现。Snippet-
placeholder未选中时的占位文字。string-
position下拉层相对触发器的方位。Position-
prefix选择框前缀,snippet。内容为文本或 Icon 时自动带上左右间隔。Snippet-
preventScroll聚焦时是否阻止浏览器滚动到元素。boolean-
remote是否为远程搜索,开启后不再在本地筛选选项,由使用方更新 optionList。booleanfalse
restTagsPopoverProps+N 浮层的 Popover 属性。PopoverProps-
searchPlaceholder搜索框在下拉列表中时(searchPosition="dropdown")搜索框的占位文字。string-
searchPosition搜索框的位置,可选 trigger、dropdown。'trigger' | 'dropdown'"trigger"
selectedItem已选内容,snippet,参数为 { option, index, disabled, onClose }。单选时替换选择框内容,多选时替换每个标签里的内容。TypeSnippet<[SelectSelectedItemSnippetProps]>-
showArrow是否显示右侧下拉箭头。booleantrue
showClear是否显示清除按钮。booleanfalse
showRestTagsPopover超过 maxTagCount 后,hover 到 +N 时是否通过 Popover 显示剩余标签。booleanfalse
size尺寸,可选 small、default、large。SelectSize-
spacing下拉层与触发器的间距。number | { x: number; y: number }-
stopPropagation是否阻止下拉层内的点击事件冒泡到外层。booleantrue
suffix选择框后缀,snippet。内容为文本或 Icon 时自动带上左右间隔。Snippet-
tag多选时替换每个标签,snippet,参数同 selectedItem,同时提供时优先于 selectedItem。TypeSnippet<[SelectSelectedItemSnippetProps]>-
trigger替换触发器的内容,snippet,参数为 { value, inputValue, placeholder, disabled, onSearch, onClear, onRemove }。TypeSnippet<[SelectTriggerSnippetProps]>-
validateStatus校验状态,可选 default、warning、error,只影响背景颜色等样式。ValidateStatus-
value当前选中的值,可 bind:value。单选为单个值,多选为数组,开启 onChangeWithObject 时为选项对象。不传时由组件自行管理;单向 value={x} 只作初值,要完全受控用函数绑定 bind:value={get, set};绑成 undefined 会清空选中。没有 defaultValue。SelectValue-
virtualize开启列表虚拟化,itemSize 必传。开启后不渲染分组标题与 role="group",选项按顺序平铺。SelectVirtualize-

Methods

方法说明类型
clearInput清空搜索框的值。Type() => void
close关闭下拉列表。Type() => void
deselectAll清空所有已选项。Type() => void
focus聚焦触发器,可搜索时聚焦搜索框并展开下拉列表。Type() => void
open展开下拉列表。Type() => void
rePosition按触发器当前位置立即重新计算下拉层位置,一般无需调用。Type() => void
search按输入了该值来搜索。Type(keyword: string, event?: Event) => void
selectAll选中所有可见且未禁用的选项,仅多选时有效。Type() => void

class、style、data-* 与原生属性和事件落在根元素上,style 不会传给下拉弹出层(用 dropdownStyle);设置 trigger 后根元素不再带有 Select 自身的样式类。aria-label、aria-labelledby、aria-describedby、aria-errormessage、aria-invalid、aria-required 落在 combobox 上;可搜索时搜索框挂载后它就是 combobox,这些属性随之移过去。

Option Props


选项以 value 作为标识,同一个 Select 内 value 不应重复;label 可以重复

Svelte 版的选项是 optionList 的条目,没有 Select.Option 子组件。条目的字段如下,class、style、data-* 落在选项行上;其他字段不会进入 DOM,随选项记录在 onSelect、onDeselect、selectedItem、tag、optionItem 与 optionLabel 中,以及开启 onChangeWithObject 后的 onChange 入参中回传。

字段说明类型默认值
value选项的值,作为标识string | number-
label选项的文本,用于显示、搜索与回调string | number-
disabled是否禁用该选项booleanfalse
showTick选中时是否显示勾选图标booleantrue
group所属分组,同一分组的条目必须相邻;没有 label 的分组不渲染标题{ key: string | number; label?: string | number }-
class选项行的类名ClassValue-
style选项行的样式,字符串string-

OptGroup Props


Svelte 版没有 Select.OptGroup,分组写在 optionList 条目的 group 字段上(见上文「分组」);分组标题用 groupLabel snippet 定制,标题元素带有 x-semi-prop="groupLabel"。

Methods

Select 经 bind:this 取得组件实例,调用下列方法:

方法说明
open()手动展开下拉列表
close()手动关闭下拉列表
focus()手动聚焦:可搜索时聚焦搜索框并展开下拉列表,否则聚焦触发器,不展开
clearInput()手动清空搜索框的值
selectAll()选中所有可见且未禁用的选项,仅多选时有效
deselectAll()清空所有已选项
search(value: string, event?: Event)按输入了该值来搜索,该值会被置给搜索框;不传事件时 onSearch 的第二个参数为 undefined
rePosition()按触发器当前位置立即重新计算下拉层位置;下拉层已随滚动、窗口尺寸变化、触发器移动以及触发器或列表的尺寸变化自动重新定位,一般无需调用;跟随触发器移动会晚一帧,需要同一帧内对齐时调用
<script lang="ts">
    import { Select } from '@fibrae/semi-ui-svelte';

    let select = $state<Select>();
</script>

<Select bind:this={select} />
<button onclick={() => select?.open()}>打开</button>

Accessibility

ARIA

  • 按 ARIA 1.2 的 combobox 写法,任一时刻只有一个元素是 combobox,弹出层的 role 为 listbox,可选项的 role 为 option:
    • 不可搜索,或搜索框在下拉内(searchPosition="dropdown")时,Select trigger 是 select-only combobox,选中的内容是它的值
    • 搜索框在 trigger 内时,搜索框本身是 combobox,带 aria-autocomplete="list",trigger 不再有角色和 Tab 停靠点。单选的搜索框只在搜索时出现,未搜索时 trigger 仍是 combobox;搜索框在输入前为空,已选文本以 aria-describedby 关联为它的描述。多选的搜索框一直存在
    • 下拉内的搜索框保持文本框角色,带 aria-controls、aria-autocomplete、aria-activedescendant,名称与 combobox 相同
  • combobox 的名称按优先级取:aria-labelledby、aria-label、实际渲染出来的 insetLabel(combobox 的 aria-labelledby 指向它,未传 insetLabelId 时组件生成 id;有 prefix 时 insetLabel 不渲染,也不作名称),都没有时为语言包中的「选择」。建议传入与表单标签一致的名称。listbox 与下拉内的搜索框使用同一个名称来源,不指向 combobox 自身。选中的内容是 combobox 的值,不计入名称
  • combobox 具有 aria-haspopup、aria-expanded、aria-controls 属性,表示它与弹出层的关系
  • 多选时,listbox aria-multiselectable 为 true,表示当前可以多选
  • Option 选中时,aria-selected 为 true;当 Option 禁用时,aria-disabled 为 true
  • 带 label 的分组(Select.OptGroup,Svelte 为 optionList 的 group)中的选项位于 role="group" 内,以分组标题为名称(aria-labelledby),读屏会读出选项所属的分组;虚拟列表不显示分组标题,不包分组
  • 下拉打开时,属性 aria-activedescendant 指向键盘聚焦的 option,保证在朗读旁白时识别到当前的选择的 option;完全自定义候选项渲染时请把参数中的 id 写在 option 元素上(更多用法请参考Managing Focus in Composites Using aria-activedescendant)

键盘和焦点

不带 Filter 功能,或搜索框在下拉内(searchPosition="dropdown")的 Select:

  • Select 聚焦后,键盘用户可以通过 空格、上箭头、下箭头(含 Alt + 下箭头)或 Enter 键打开下拉菜单。已有选中值时焦点落在第一个已选的选项上,直接按 Enter 不改变值;没有选中值时保留当前高亮,初始高亮为第一个未禁用的选项(defaultActiveFirstOption 默认为 true)
  • Home、End 打开下拉菜单,并把焦点移到第一个、最后一个可用选项
  • 输入字符打开下拉菜单,并把焦点移到下一个以该字符开头的选项;快速连续输入时按整串匹配,重复输入同一字符时在以它开头的选项间轮换
  • 当下拉菜单打开时:
    • 使用 Esc 键或 Tab 键可以关闭菜单
    • 使用 上箭头 或 下箭头 可以切换选项,Home、End 移到首尾,输入字符移到以它开头的选项
    • 被聚焦的选项可以通过 Enter 或 空格 选中:单选选中后收起面板,多选切换选中状态并保持打开。快速连续输入字符的过程中,空格 计入匹配的字符串,不选中选项。焦点在下拉内的搜索框时,Home、End、空格 与字符用于编辑搜索内容,不移动选项焦点
  • 多选时焦点在已选标签上,按键只作用于标签:Backspace、Delete 删除标签,Enter、空格 不打开下拉菜单、不改变选中值
  • 当焦点在下拉菜单中,且用户使用的 innerBottomSlot 或 outerBottomSlot 属性的自定义 slot 中含有可交互元素时:
    • 可以使用 Tab 键切换到这些可交互元素上
    • 当焦点在自定义 slot 的首个可交互元素上时,使用 Shift + Tab ,焦点回到 Select 框上

带 Filter 功能的 Select:

  • Select 聚焦后,键盘用户可以通过 上箭头 或 下箭头 或 Enter 键打开下拉菜单。此时焦点仍然处于 Select 框,用户可以输入内容,同时也能使用 上箭头 或 下箭头 切换选项
  • 当下拉菜单打开时:使用 上箭头 或 下箭头 切换选项;Enter 选中被聚焦的选项,单选选中后收起面板,多选切换选中状态并保持打开;Esc 或 Tab 关闭菜单。Home、End、空格 与字符留给 Select 框内的输入框,用于编辑搜索内容,不移动选项焦点
  • 当焦点在 Select 框上,且用户使用的 innerBottomSlot 或 outerBottomSlot 属性的自定义 slot 中含有可交互元素时:
    • 可以使用 Tab 键切换到这些可交互元素上
    • 当焦点在自定义 slot 的首个可交互元素上时,使用 Shift + Tab ,焦点回到 Select 框上

清除按钮:

  • showClear 开启、有已选值或搜索文本且未禁用时,trigger 内渲染清除按钮。它是原生 button,名称为语言包中的「清空已选值」,在 hover、下拉打开或焦点位于 Select 内时显示
  • 焦点在 Select 框上时按 Tab 移到清除按钮,Enter 或 Space 清空,效果与鼠标点击相同;清空后焦点回到 Select 框

文案规范

  • 选择器标签
    • 用 1-3 个词描述需要用户所做的输入
    • 使用语句书写规范(首字母大写,其余小写)
    • 避免使用标点符号和介词(“the”, “an”, “a”)
    • 标签需是独立语句。不要让标签是前半句语句,选项是后半句语句。
    • 使用描述性语句,而不是指示性语句。如果选项需要更多解释,可以在选择框下使用帮助文本。
  • 选择器选项
    • 如果没有默认选项,就使用“Select”做占位文案
    • 选项要按首字母顺序或者其他有逻辑的排列顺序,使用户更好地找到选项
    • 使用语句书写规范(首字母大写,其余小写),避免在句尾使用逗号和分号
    • 清晰表达出选项所表示的选择目的

设计变量

下表是组件内部的 Sass 变量,不能覆写。定制样式请覆写 --semi-* CSS 变量(见 Design Token 页),或写不分层的 CSS 规则。
Sass 变量值用法
$transition_duration-select-bgvar(--semi-transition_duration-none)选择器-背景色-动画持续时间
$transition_function-select-bgvar(--semi-transition_function-easeIn)选择器-背景色-过渡曲线
$transition_delay-select-bgvar(--semi-transition_delay-none)选择器-背景色-延迟时间
$transition_duration-select-bordervar(--semi-transition_duration-none)选择器-边框-动画持续时间
$transition_function-select-bordervar(--semi-transition_function-easeIn)选择器-边框-过渡曲线
$transition_delay-select-bordervar(--semi-transition_delay-none)选择器-边框-延迟时间
$transition_duration-select_option-bgvar(--semi-transition_duration-none)选择器-选项-动画持续时间
$transition_function-select_option-bgvar(--semi-transition_function-easeIn)选择器-选项-过渡曲线
$transition_delay-select_option-bgvar(--semi-transition_delay-none)选择器-选项-延迟时间
$transform_scale-selectvar(--semi-transform_scale-none)选择框-变大
$transform_rotate-select-arrowvar(--semi-transform_rotate-none)选择框-箭头-旋转
$color-select-bg-defaultvar(--semi-color-fill-0)选择器输入框背景色 - 默认态
$color-select-bg-hovervar(--semi-color-fill-1)选择器输入框背景色 - 悬停态
$color-select-bg-activevar(--semi-color-fill-2)选择器输入框背景色 - 按下态
$color-select-bg-focusvar(--semi-color-fill-0)选择器输入框背景色 - 聚焦态
$color-select-border-defaulttransparent选择器输入框描边颜色
$color-select-border-hover$color-select-border-default选择器输入框描边颜色 - 悬浮
$color-select-border-activevar(--semi-color-focus-border)选择器输入框描边颜色 - 按下态
$color-select-border-focus$color-select-border-active选择器输入框描边颜色 - 选中态
$color-select_dropdown_input-border$color-select-border-default下拉搜索框底部描边颜色
$color-select_warning-bg-defaultvar(--semi-color-warning-light-default)警示选择器输入框背景色 - 默认态
$color-select_warning-border-defaultvar(--semi-color-warning-light-default)警示选择器输入框描边颜色 - 默认态
$color-select_warning-bg-hovervar(--semi-color-warning-light-hover)警示选择器输入框背景色 - 悬停态
$color-select_warning-border-hovervar(--semi-color-warning-light-hover)警示选择器输入框描边颜色 - 悬停态
$color-select_warning-bg-focusvar(--semi-color-warning-light-default)警示选择器输入框背景色 - 选中态
$color-select_warning-border-focusvar(--semi-color-warning)警示选择器输入框描边颜色 - 选中态
$color-select_warning-bg-activevar(--semi-color-warning-light-active)警示选择器输入框背景色 - 按下态
$color-select_warning-border-activevar(--semi-color-warning-light-active)警示选择器输入框描边颜色 - 按下态
$color-select_danger-bg-defaultvar(--semi-color-danger-light-default)报错选择器输入框背景色 - 默认态
$color-select_danger-border-defaultvar(--semi-color-danger-light-default)报错选择器输入框描边颜色 - 默认态
$color-select_danger-bg-hovervar(--semi-color-danger-light-hover)报错选择器输入框背景色 - 悬停态
$color-select_danger-border-hovervar(--semi-color-danger-light-hover)报错选择器输入框描边颜色 - 悬停态
$color-select_danger-bg-focusvar(--semi-color-danger-light-default)报错选择器输入框背景色 - 选中态
$color-select_danger-border-focusvar(--semi-color-danger)报错选择器输入框描边颜色 - 选中态
$color-select_danger-bg-activevar(--semi-color-danger-light-active)报错选择器输入框背景色 - 按下态
$color-select_danger-border-activevar(--semi-color-danger-light-active)报错选择器输入框描边颜色 - 按下态
$color-select_default-border-focusvar(--semi-color-focus-border)默认选择器输入框描边颜色 - 选中态
$color-select_main-text-defaultvar(--semi-color-text-0)选择器输入框回填内容文本颜色
$color-select-icon-defaultvar(--semi-color-text-2)选择器输入框图标颜色
$color-select_clearBtn-text-defaultvar(--semi-color-text-2)选择器输入框清空按钮颜色 - 默认态
$color-select_clearBtn-text-hovervar(--semi-color-primary)选择器输入框清空按钮颜色 - 悬停态
$color-select_input_disabled-bgvar(--semi-color-disabled-fill)禁用选择器输入框背景色
$color-select_input_disabled-border-focustransparent禁用选择器输入框描边颜色 - 聚焦态
$color-select_input_disabled-textvar(--semi-color-disabled-text)禁用选择器输入框回填内容文字颜色
$color-select_input_disabled-bg-hovervar(--semi-color-disabled-fill)禁用选择器输入框背景色 - 悬停态
$color-select_input_disabled-bg-focusvar(--semi-color-disabled-fill)禁用选择器输入框背景色 - 聚焦态
$color-select_input_placeholder-textvar(--semi-color-text-2)选择器输入框占位文本文字颜色
$color-select_option_main-textvar(--semi-color-text-0)选择器下拉菜单选项文本颜色
$color-select_option_keyword-textvar(--semi-color-primary)选择器下拉菜单选项匹配搜索结果文本颜色
$color-select_option-icon-defaulttransparent选择器下拉菜单选项图标颜色 - 默认态
$color-select_option-bg-hovervar(--semi-color-fill-0)选择器下拉菜单选项背景颜色 - 悬停态
$color-select_option-bg-activevar(--semi-color-fill-1)选择器下拉菜单选项背景颜色 - 按下态
$color-select_option_disabled-textvar(--semi-color-disabled-text)禁用选择器下拉菜单选项文字颜色
$color-select_option-icon-activevar(--semi-color-text-2)选择器下拉菜单选项图标颜色 - 选中态
$color-select_option-border-defaultvar(--semi-color-border)选择器下拉菜单分组标题分割线颜色
$color-select-option-bg-selectedtransparent选择器下拉菜单选项背景颜色 - 选中态
$color-select_create_tips-textvar(--semi-color-text-2)选择器下拉菜单新建选项提示文本颜色
$color-select_group-textvar(--semi-color-text-2)选择器下拉菜单分组标题文本颜色
$color-select_prefix_suffix_text-defaultvar(--semi-color-text-2)选择器输入框前后缀文本颜色
$height-select_large$height-control-large选择器输入框高度 - 大尺寸
$height-select_small$height-control-small选择器输入框高度 - 小尺寸
$height-select_default$height-control-default选择器输入框高度 - 默认尺寸
$width-select_option_tick$width-icon-small选择器下拉菜单项选中对勾图标大小
$width-select-border1px选择器输入框描边宽度
$width-select_arrow32px选择器输入框下拉箭头宽度
$width-select_arrow_empty12px选择器输入框下拉箭头为空时(有suffix icon)宽度
$width-select_clear-icon32px选择器输入框清空按钮宽度
$width-select_group_top-border$border-thickness-control选择器下拉菜单分组标题描边宽度
$height-select_multiple_input_small20px小尺寸多项选择器输入框Input框高度
$height-select_multiple_input_default24px默认多项选择器输入框Input框高度
$height-select_multiple_input_large24px大尺寸多项选择器输入框Input框高度
$width-select-border-hover$width-select-border选择器输入框描边宽度 - 悬浮
$width-select-border-focus$width-select-border-hover选择器输入框描边宽度 - 按下
$width-select-border-active$width-select-border-focus选择器输入框描边宽度 - 选中
$spacing-select_option_tick-marginRight$spacing-tight选择器下拉菜单选中对勾右侧外边距
$spacing-select_prefix_suffix_text-marginX$spacing-base-tight选择器输入框前后缀文本水平内边距
$spacing-select_prefix_suffix_text-marginY0px选择器输入框前后缀文本垂直内边距
$spacing-select_prefix_suffix_icon-marginX$spacing-tight选择器输入框前后缀图标水平内边距
$spacing-select_prefix_suffix_icon-marginY0px选择器输入框前后缀图标垂直内边距
$spacing-select_create_tips-marginRight$spacing-extra-tight创建新选项右侧外边距
$spacing-select_group-marginTop$spacing-extra-tight选择器下拉菜单分组标题顶部外边距
$spacing-select_group-paddingTop$spacing-base-tight选择器下拉菜单分组标题顶部内边距
$spacing-select_group-paddingBottom$spacing-extra-tight选择器下拉菜单分组标题底部内边距
$spacing-select_group-paddingLeft$spacing-base-tight + $width-select_option_tick + $spacing-select_option_tick-marginRight选择器下拉菜单分组标题左侧内边距
$spacing-select_group-paddingRight$spacing-base选择器下拉菜单分组标题右侧内边距
$spacing-select_loading_wrapper-paddingLeft$spacing-base选择器加载左侧内边距
$spacing-select_loading_wrapper-paddingRight$spacing-base选择器加载右侧内边距
$spacing-select_loading_wrapper-paddingTop$spacing-tight选择器加载顶部内边距
$spacing-select_loading_wrapper-paddingBottom$spacing-tight选择器加载底部内边距
$spacing-select_multiple_content_wrapper_empty-marginLeft$spacing-tight多项选择器空回填内容为空时左侧内边距
$spacing-select_multiple_selection-marginLeft$spacing-extra-tight多项选择器回填内容左侧内边距
$spacing-select_option-paddingLeft$spacing-base-tight选择器下拉菜单项左侧内边距
$spacing-select_option-paddingRight$spacing-base-tight选择器下拉菜单项右侧内边距
$spacing-select_option-paddingTop$spacing-tight选择器下拉菜单项顶部内边距
$spacing-select_option-paddingBottom$spacing-tight选择器下拉菜单项底部内边距
$spacing-select_tag-marginTop$spacing-super-tight - 1px多项选择器标签顶部外边距
$spacing-select_tag-marginRight$spacing-extra-tight多项选择器标签右侧外边距
$spacing-select_tag-marginBottom$spacing-super-tight - 1px多项选择器标签底部外边距
$spacing-select_selection-marginLeft$spacing-base-tight选择器内容区左侧外边距
$spacing-select_option_list-paddingTop$spacing-extra-tight选择器内容区顶部内边距
$spacing-select_option_list-paddingRight0px选择器内容区右侧内边距
$spacing-select_option_list-paddingBottom$spacing-extra-tight选择器内容区底部内边距
$spacing-select_option_list-paddingLeft0px选择器内容区左侧内边距
$spacing-select_dropdown_input_paddingTop8px下拉搜索框顶部内边距
$spacing-select_dropdown_input_paddingBottom8px下拉搜索框底部内边距
$spacing-select_dropdown_input_paddingRight12px下拉搜索框右侧内边距
$spacing-select_dropdown_input_paddingLeft12px下拉搜索框左侧内边距
$radius-selectvar(--semi-border-radius-small)选择器输入框圆角
$radius-select_option0px选择器待选项圆角
$font-select-fontWeight$font-weight-regular选择器文本字重
$font-select_keyword-fontWeight600选择器搜索结果命关键词中文本字重
$font-select_prefix_suffix-fontWeight$font-weight-bold选择器输入框前后缀文本字重
$opacity-select_selection_text_inactive0.4

TypeScript 泛型支持

FAQ

  • 可搜索的 Select,使用远程数据动态更新optionList,为什么在异步请求完成之前有时候会出现暂无数据?
    请检查是否开启了 remote,不开启 remote 的情况下,默认会将 input 框输入值与当前的 optionList 进行一次对比筛选,如果无匹配时,就会显示暂无数据。
    可以通过开启 remote 关闭对本地当前数据的匹配筛选。

  • Select 会自动限制下拉菜单的宽度吗?

    • 会给 minWidth,但不会写死 width。如果有需要的话,可以自己通过 dropdownStyle 来添加。
  • 为什么单选选择选项后没有触发 blur 事件?

    • 在 V2.17.0 前,Select 单选选择后,会触发 Select 的 blur 事件。
    • 在 V2.17.0 后,Select 增加了 A11y 支持,不会触发 Select 的 blur 事件。
      • 单选选择中,Select 浮层关闭,依然保持焦点在 trigger(此时可以通过 Enter 回车键再次打开 Select 浮层)
      • 无论单选或多选,按下 Esc,仅 Select 浮层关闭,trigger 保持焦点(此时可以通过 Enter 回车键再次打开 Select 浮层)