Skip to content

Select 选择器

下拉选择器。

代码演示

基础用法

use a-select-option

Lucy
Lucy
Lucy

use options (recommend)

Lucy
Lucy
Lucy
vue
<template>
  <h2>use a-select-option</h2>
  <a-space>
    <a-select
      ref="select"
      v-model:value="value1"
      style="width: 120px"
      @focus="focus"
      @change="handleChange"
    >
      <a-select-option value="jack">Jack</a-select-option>
      <a-select-option value="lucy">Lucy</a-select-option>
      <a-select-option value="disabled" disabled>Disabled</a-select-option>
      <a-select-option value="Yiminghe">yiminghe</a-select-option>
    </a-select>
    <a-select v-model:value="value2" style="width: 120px" disabled>
      <a-select-option value="lucy">Lucy</a-select-option>
    </a-select>
    <a-select v-model:value="value3" style="width: 120px" loading>
      <a-select-option value="lucy">Lucy</a-select-option>
    </a-select>
  </a-space>
  <h2 style="margin-top: 10px">use options (recommend)</h2>
  <a-space>
    <a-select
      ref="select"
      v-model:value="value1"
      style="width: 120px"
      :options="options1"
      @focus="focus"
      @change="handleChange"
    ></a-select>
    <a-select v-model:value="value2" style="width: 120px" disabled :options="options2"></a-select>
    <a-select v-model:value="value3" style="width: 120px" loading :options="options3"></a-select>
  </a-space>
</template>
<script setup>
import { ref } from 'vue';
const value1 = ref('lucy');
const value2 = ref('lucy');
const value3 = ref('lucy');
const options1 = ref([
  {
    value: 'jack',
    label: 'Jack',
  },
  {
    value: 'lucy',
    label: 'Lucy',
  },
  {
    value: 'disabled',
    label: 'Disabled',
    disabled: true,
  },
  {
    value: 'yiminghe',
    label: 'Yiminghe',
  },
]);
const options2 = ref([
  {
    value: 'lucy',
    label: 'Lucy',
  },
]);
const options3 = ref([
  {
    value: 'lucy',
    label: 'Lucy',
  },
]);
const focus = () => {
  console.log('focus');
};
const handleChange = value => {
  console.log(`selected ${value}`);
};
</script>

标签

tags select,随意输入的内容(scroll the menu)

vue
<template>
  <a-select
    v-model:value="value"
    mode="tags"
    style="width: 100%"
    placeholder="Tags Mode"
    :options="options"
    @change="handleChange"
  ></a-select>
</template>
<script setup>
import { ref } from 'vue';
const handleChange = value => {
  console.log(`selected ${value}`);
};
const value = ref([]);
const options = [...Array(25)].map((_, i) => ({
  value: (i + 10).toString(36) + (i + 1),
}));
</script>

最多显示多少个选项及选项最大长度

设置一个数字,超过后自动折叠。 maxTagCount 也可以设置成响应式,但响应式对性能有所消耗,不推荐在大表单场景下使用。

maxTagCount: 2

maxTagCount: responsive

maxTagTextLength: 10

vue
<template>
  <a-space direction="vertical" style="width: 100%">
    <a-space>
      <a-button type="primary" @click="maxTagCount++">maxTagCount++</a-button>
      <a-button type="primary" @click="maxTagCount--">maxTagCount--</a-button>
    </a-space>

    <h2>maxTagCount: {{ maxTagCount }}</h2>
    <a-select
      v-model:value="value"
      mode="multiple"
      style="width: 100%"
      placeholder="Select Item..."
      :max-tag-count="maxTagCount"
      :options="options"
    >
      <template #maxTagPlaceholder="omittedValues">
        <span style="color: red">+ {{ omittedValues.length }} ...</span>
      </template>
    </a-select>
    <h2>maxTagCount: responsive</h2>
    <a-select
      v-model:value="value"
      mode="multiple"
      style="width: 100%"
      placeholder="Select Item..."
      max-tag-count="responsive"
      :options="options"
    ></a-select>
    <a-space>
      <a-button type="primary" @click="maxTagTextLength++">maxTagTextLength++</a-button>
      <a-button type="primary" @click="maxTagTextLength--">maxTagTextLength--</a-button>
    </a-space>
    <h2>maxTagTextLength: {{ maxTagTextLength }}</h2>
    <a-select
      v-model:value="value"
      mode="multiple"
      style="width: 100%"
      placeholder="Select Item..."
      :max-tag-text-length="maxTagTextLength"
      :options="options"
    ></a-select>
  </a-space>
</template>
<script setup>
import { ref } from 'vue';
const options = ref([]);
for (let i = 10; i < 36; i++) {
  const value = i.toString(36) + i;
  options.value.push({
    label: `Long Label: ${value}`,
    value,
  });
}
const maxTagCount = ref(2);
const maxTagTextLength = ref(10);
const value = ref(['a10', 'c12', 'h17', 'j19', 'k20']);
</script>

自动分词

试下复制 露西,杰克 到输入框里。只在 tags 和 multiple 模式下可用。

vue
<template>
  <a-select
    v-model:value="value"
    mode="tags"
    style="width: 100%"
    :token-separators="[',']"
    placeholder="Automatic tokenization"
    :options="options"
    @change="handleChange"
  ></a-select>
</template>
<script setup>
import { ref, watch } from 'vue';
const options = ref([
  {
    value: 'a1',
    label: 'a1',
  },
]);
const value = ref([]);
const handleChange = value => {
  console.log(`selected ${value}`);
};
watch(value, () => {
  console.log('value', value.value);
});
</script>

多选

多选,从已有条目中选择(scroll the menu)

vue
<template>
  <a-select
    v-model:value="value"
    mode="multiple"
    style="width: 100%"
    placeholder="Please select"
    :options="[...Array(25)].map((_, i) => ({ value: (i + 10).toString(36) + (i + 1) }))"
    @change="handleChange"
  ></a-select>
</template>
<script setup>
import { ref } from 'vue';
const handleChange = value => {
  console.log(`selected ${value}`);
};
const value = ref(['a1', 'b2']);
</script>

分组

OptGroupoptions.options 进行选项分组。

Lucy
Lucy
vue
<template>
  <a-space>
    <a-select v-model:value="value" style="width: 200px" @change="handleChange">
      <a-select-opt-group>
        <template #label>
          <span>
            <user-outlined />
            Manager
          </span>
        </template>
        <a-select-option value="jack">Jack</a-select-option>
        <a-select-option value="lucy">Lucy</a-select-option>
      </a-select-opt-group>
      <a-select-opt-group label="Engineer">
        <a-select-option value="Yiminghe">yiminghe</a-select-option>
        <a-select-option value="Yiminghe1">yiminghe1</a-select-option>
      </a-select-opt-group>
    </a-select>
    <a-select
      v-model:value="value"
      :options="options"
      style="width: 200px"
      @change="handleChange"
    ></a-select>
  </a-space>
</template>
<script setup>
import { ref } from 'vue';
const handleChange = value => {
  console.log(`selected ${value}`);
};
const options = ref([
  {
    label: 'Manager',
    options: [
      {
        value: 'jack',
        label: 'Jack',
      },
      {
        value: 'lucy',
        label: 'Lucy',
      },
    ],
  },
  {
    label: 'Engineer',
    options: [
      {
        value: 'yiminghe',
        label: 'Yiminghe',
      },
    ],
  },
]);
const value = ref(['lucy']);
</script>

联动

省市联动是典型的例子。 推荐使用 Cascader 组件。

Zhejiang
Hangzhou
vue
<template>
  <a-space>
    <a-select
      v-model:value="province"
      style="width: 120px"
      :options="provinceData.map(pro => ({ value: pro }))"
    ></a-select>
    <a-select
      v-model:value="secondCity"
      style="width: 120px"
      :options="cities.map(city => ({ value: city }))"
    ></a-select>
  </a-space>
</template>
<script setup>
import { computed, ref, watch } from 'vue';
const provinceData = ['Zhejiang', 'Jiangsu'];
const cityData = {
  Zhejiang: ['Hangzhou', 'Ningbo', 'Wenzhou'],
  Jiangsu: ['Nanjing', 'Suzhou', 'Zhenjiang'],
};
const province = ref(provinceData[0]);
const secondCity = ref(cityData[province.value][0]);
const cities = computed(() => {
  return cityData[province.value];
});
watch(province, val => {
  secondCity.value = cityData[val][0];
});
</script>

带搜索框

展开后可对选项进行搜索。

vue
<template>
  <a-select
    v-model:value="value"
    show-search
    placeholder="Select a person"
    style="width: 200px"
    :options="options"
    :filter-option="filterOption"
    @focus="handleFocus"
    @blur="handleBlur"
    @change="handleChange"
  ></a-select>
</template>
<script setup>
import { ref } from 'vue';
const options = ref([
  {
    value: 'jack',
    label: 'Jack',
  },
  {
    value: 'lucy',
    label: 'Lucy',
  },
  {
    value: 'tom',
    label: 'Tom',
  },
]);
const handleChange = value => {
  console.log(`selected ${value}`);
};
const handleBlur = () => {
  console.log('blur');
};
const handleFocus = () => {
  console.log('focus');
};
const filterOption = (input, option) => {
  return option.value.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};
const value = ref(undefined);
</script>

弹出位置

可以通过 placement 手动指定弹出的位置。



HangZhou #310000
vue
<template>
  <a-radio-group v-model:value="placement">
    <a-radio-button value="topLeft">topLeft</a-radio-button>
    <a-radio-button value="topRight">topRight</a-radio-button>
    <a-radio-button value="bottomLeft">bottomLeft</a-radio-button>
    <a-radio-button value="bottomRight">bottomRight</a-radio-button>
  </a-radio-group>
  <br />
  <br />
  <a-select
    v-model:value="value"
    style="width: 120px"
    :dropdown-match-select-width="false"
    :placement="placement"
  >
    <a-select-option value="HangZhou">HangZhou #310000</a-select-option>
    <a-select-option value="NingBo">NingBo #315000</a-select-option>
    <a-select-option value="WenZhou">WenZhou #325000</a-select-option>
  </a-select>
</template>
<script setup>
import { ref } from 'vue';
const placement = ref('topLeft');
const value = ref('HangZhou');
</script>

自定义状态

使用 status 为 DatePicker 添加状态,可选 error 或者 warning

vue
<template>
  <a-space direction="vertical" style="width: 100%">
    <a-select status="error" style="width: 100%" />
    <a-select status="warning" style="width: 100%" />
  </a-space>
</template>

<style scoped>
#components-select-demo-status .ant-select {
  margin: 0;
}
</style>

API

html
<a-select>
  <a-select-option value="lucy">lucy</a-select-option>
</a-select>

Select props

参数说明类型默认值
allowClear支持清除booleanfalse
autoClearSearchValue是否在选中项后清空搜索框,只在 mode 为 multiple 或 tags 时有效。booleantrue
autofocus默认获取焦点booleanfalse
bordered是否有边框booleantrue
clearIcon自定义的多选框清空图标VNode | slot-
defaultActiveFirstOption是否默认高亮第一个选项。booleantrue
defaultOpen是否默认展开下拉菜单boolean-
disabled是否禁用booleanfalse
popupClassName下拉菜单的 className 属性string-
dropdownMatchSelectWidth下拉菜单和选择器同宽。默认将设置 min-width,当值小于选择框宽度时会被忽略。false 时会关闭虚拟滚动boolean | numbertrue
dropdownMenuStyledropdown 菜单自定义样式object-
dropdownRender自定义下拉框内容({menuNode: VNode, props}) => VNode | v-slot-
dropdownStyle下拉菜单的 style 属性object-
fieldNames自定义节点 label、value、options 的字段object{ label: label, value: value, options: options }
filterOption是否根据输入项进行筛选。当其为一个函数时,会接收 inputValue option 两个参数,当 option 符合筛选条件时,应返回 true,反之则返回 false。boolean | function(inputValue, option)true
filterSort搜索时对筛选结果项的排序函数, 类似Array.sort里的 compareFunction(optionA: Option, optionB: Option) => number-
firstActiveValue默认高亮的选项string | string[]-
getPopupContainer菜单渲染父节点。默认渲染到 body 上,如果你遇到菜单滚动定位问题,试试修改为滚动的区域,并相对其定位。function(triggerNode)() => document.body
labelInValue是否把每个选项的 label 包装到 value 中,会把 Select 的 value 类型从 string 变为 {key: string, label: vNodes, originLabel: any} 的格式, originLabel(3.1) 保持原始类型,如果通过 a-select-option children 构造的节点,该值是是个函数(即 a-select-option 的默认插槽)booleanfalse
listHeight设置弹窗滚动高度number256
maxTagCount最多显示多少个 tagnumber-
maxTagPlaceholder隐藏 tag 时显示的内容slot | function(omittedValues)-
maxTagTextLength最大显示的 tag 文本长度number-
menuItemSelectedIcon自定义当前选中的条目图标VNode | slot-
mode设置 Select 的模式为多选或标签'multiple' | 'tags' | 'combobox'-
notFoundContent当下拉列表为空时显示的内容string | slotNot Found
open是否展开下拉菜单boolean-
option通过 option 插槽,自定义节点v-slot:option="{value, label, [disabled, key, title]}"-
optionFilterProp搜索时过滤对应的 option 属性,不支持 childrenstringvalue
optionLabelProp回填到选择框的 Option 的属性值,默认是 Option 的子元素。比如在子元素需要高亮效果时,此值可以设为 value。stringchildren | label(设置 options 时)
optionsoptions 数据,如果设置则不需要手动构造 selectOption 节点Array<{value, label, [disabled, key, title]}>[]
placeholder选择框默认文字string | slot-
placement选择框弹出的位置bottomLeft bottomRight topLeft topRightbottomLeft
removeIcon自定义的多选框清除图标VNode | slot-
searchValue控制搜索文本string-
showArrow是否显示下拉小箭头boolean单选为 true,多选为 false
showSearch配置是否可搜索boolean单选为 false,多选为 true
size选择框大小,可选 large smallstringdefault
status设置校验状态'error' | 'warning'-
suffixIcon自定义的选择框后缀图标VNode | slot-
tagRender自定义 tag 内容 render,仅在 mode 为 multiple 或 tags 时生效slot(props) => any
tokenSeparators自动分词的分隔符,仅在 mode="tags" 时生效string[]-
value(v-model)指定当前选中的条目string |string[] |number | number[]-
virtual设置 false 时关闭虚拟滚动booleantrue

TIP

如果发现下拉菜单跟随页面滚动,或者需要在其他弹层中触发 Select,请尝试使用 getPopupContainer={triggerNode => triggerNode.parentNode} 将下拉弹层渲染节点固定在触发器的父元素中。

事件

事件名称说明回调参数
blur失去焦点的时回调function
change选中 option,或 input 的 value 变化(combobox 模式下)时,调用此函数function(value, option:Option | Array<Option>)
deselect取消选中时调用,参数为选中项的 value (或 key) 值,仅在 multiple 或 tags 模式下生效function(value,option:Option)
dropdownVisibleChange展开下拉菜单的回调function(open)
focus获得焦点时回调function
inputKeyDown键盘按下时回调function
mouseenter鼠标移入时回调function
mouseleave鼠标移出时回调function
popupScroll下拉列表滚动时的回调function
search文本框值变化时回调function(value: string)
select被选中时调用,参数为选中项的 value (或 key) 值function(value, option:Option)

Select Methods

名称说明
blur()取消焦点
focus()获取焦点

Option props

参数说明类型默认值
classOption 器类名string-
disabled是否禁用booleanfalse
key和 value 含义一致。如果 Vue 需要你设置此项,此项值与 value 的值相同,然后可以省略 value 设置string
title选中该 Option 后,Select 的 titlestring-
value默认根据此属性值进行筛选string | number-

OptGroup props

参数说明类型默认值
keystring-
label组名string | function(h) | slot-

FAQ

点击 dropdownRender 里的内容浮层关闭怎么办?

自定义内容点击时会关闭浮层,如果不喜欢关闭,可以通过取消点击事件的默认行为进行阻止。 看下 dropdownRender 例子 里的说明。

为什么 placeholder 不显示 ?

placeholder 只有在 value = undefined 才会显示,对于其它的 null、0、'' 等等对于 JS 语言都是有意义的值。