Select 选择器

下拉选择器。

何时使用

  • 弹出一个下拉菜单给用户选择操作,用于代替原生的选择器,或者需要一个更优雅的多选器时。
  • 当选项少时(少于 5 项),建议直接将选项平铺,使用 Radio 是更好的选择。

代码演示

Select 选择器 - 图1

基本使用

基本使用。

  1. <template>
  2. <div>
  3. <a-select defaultValue="lucy" style="width: 120px" @change="handleChange">
  4. <a-select-option value="jack">Jack</a-select-option>
  5. <a-select-option value="lucy">Lucy</a-select-option>
  6. <a-select-option value="disabled" disabled>Disabled</a-select-option>
  7. <a-select-option value="Yiminghe">yiminghe</a-select-option>
  8. </a-select>
  9. <a-select defaultValue="lucy" style="width: 120px" disabled>
  10. <a-select-option value="lucy">Lucy</a-select-option>
  11. </a-select>
  12. <a-select defaultValue="lucy" style="width: 120px" loading>
  13. <a-select-option value="lucy">Lucy</a-select-option>
  14. </a-select>
  15. </div>
  16. </template>
  17. <script>
  18. export default {
  19. methods: {
  20. handleChange(value) {
  21. console.log(`selected ${value}`);
  22. },
  23. },
  24. };
  25. </script>

Select 选择器 - 图2

三种大小

三种大小的选择框,当 size 分别为 largesmall 时,输入框高度为 40px24px ,默认高度为 32px

  1. <template>
  2. <div>
  3. <a-radio-group v-model="size">
  4. <a-radio-button value="large">Large</a-radio-button>
  5. <a-radio-button value="default">Default</a-radio-button>
  6. <a-radio-button value="small">Small</a-radio-button>
  7. </a-radio-group>
  8. <br /><br />
  9. <a-select :size="size" defaultValue="a1" style="width: 200px" @change="handleChange">
  10. <a-select-option v-for="i in 25" :key="(i + 9).toString(36) + i">
  11. {{(i + 9).toString(36) + i}}
  12. </a-select-option>
  13. </a-select>
  14. <br />
  15. <a-select
  16. mode="multiple"
  17. :size="size"
  18. placeholder="Please select"
  19. :defaultValue="['a1', 'b2']"
  20. style="width: 200px"
  21. @change="handleChange"
  22. @popupScroll="popupScroll"
  23. >
  24. <a-select-option v-for="i in 25" :key="(i + 9).toString(36) + i">
  25. {{(i + 9).toString(36) + i}}
  26. </a-select-option>
  27. </a-select>
  28. <br />
  29. <a-select
  30. mode="tags"
  31. :size="size"
  32. placeholder="Please select"
  33. :defaultValue="['a1', 'b2']"
  34. style="width: 200px"
  35. @change="handleChange"
  36. >
  37. <a-select-option v-for="i in 25" :key="(i + 9).toString(36) + i">
  38. {{(i + 9).toString(36) + i}}
  39. </a-select-option>
  40. </a-select>
  41. </div>
  42. </template>
  43. <script>
  44. export default {
  45. data() {
  46. return {
  47. size: 'default',
  48. };
  49. },
  50. methods: {
  51. handleChange(value) {
  52. console.log(`Selected: ${value}`);
  53. },
  54. popupScroll() {
  55. console.log('popupScroll');
  56. },
  57. },
  58. };
  59. </script>

Select 选择器 - 图3

标签

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

  1. <template>
  2. <a-select mode="tags" style="width: 100%" @change="handleChange" placeholder="Tags Mode">
  3. <a-select-option v-for="i in 25" :key="(i + 9).toString(36) + i"
  4. >{{(i + 9).toString(36) + i}}</a-select-option
  5. >
  6. </a-select>
  7. </template>
  8. <script>
  9. export default {
  10. methods: {
  11. handleChange(value) {
  12. console.log(`selected ${value}`);
  13. },
  14. },
  15. };
  16. </script>

Select 选择器 - 图4

自动分词

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

  1. <template>
  2. <a-select mode="tags" style="width: 100%" :tokenSeparators="[',']" @change="handleChange">
  3. <a-select-option v-for="i in 25" :key="(i + 9).toString(36) + i"
  4. >{{(i + 9).toString(36) + i}}</a-select-option
  5. >
  6. </a-select>
  7. </template>
  8. <script>
  9. export default {
  10. methods: {
  11. handleChange(value) {
  12. console.log(`selected ${value}`);
  13. },
  14. },
  15. };
  16. </script>

Select 选择器 - 图5

获得选项的文本

默认情况下 onChange 里只能拿到 value,如果需要拿到选中的节点文本 label,可以使用 labelInValue 属性。选中项的 label 会被包装到 value 中传递给 onChange 等函数,此时 value 是一个对象。

  1. <template>
  2. <a-select
  3. labelInValue
  4. :defaultValue="{ key: 'lucy' }"
  5. style="width: 120px"
  6. @change="handleChange"
  7. >
  8. <a-select-option value="jack">Jack (100)</a-select-option>
  9. <a-select-option value="lucy">Lucy (101)</a-select-option>
  10. </a-select>
  11. </template>
  12. <script>
  13. export default {
  14. methods: {
  15. handleChange(value) {
  16. console.log(value); // { key: "lucy", label: "Lucy (101)" }
  17. },
  18. },
  19. };
  20. </script>

Select 选择器 - 图6

多选

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

  1. <template>
  2. <a-select
  3. mode="multiple"
  4. :defaultValue="['a1', 'b2']"
  5. style="width: 100%"
  6. @change="handleChange"
  7. placeholder="Please select"
  8. >
  9. <a-select-option v-for="i in 25" :key="(i + 9).toString(36) + i"
  10. >{{(i + 9).toString(36) + i}}</a-select-option
  11. >
  12. </a-select>
  13. </template>
  14. <script>
  15. export default {
  16. methods: {
  17. handleChange(value) {
  18. console.log(`selected ${value}`);
  19. },
  20. },
  21. };
  22. </script>

Select 选择器 - 图7

联动

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

  1. <template>
  2. <div>
  3. <a-select :defaultValue="provinceData[0]" style="width: 120px" @change="handleProvinceChange">
  4. <a-select-option v-for="province in provinceData" :key="province"
  5. >{{province}}</a-select-option
  6. >
  7. </a-select>
  8. <a-select v-model="secondCity" style="width: 120px">
  9. <a-select-option v-for="city in cities" :key="city">{{city}}</a-select-option>
  10. </a-select>
  11. </div>
  12. </template>
  13. <script>
  14. const provinceData = ['Zhejiang', 'Jiangsu'];
  15. const cityData = {
  16. Zhejiang: ['Hangzhou', 'Ningbo', 'Wenzhou'],
  17. Jiangsu: ['Nanjing', 'Suzhou', 'Zhenjiang'],
  18. };
  19. export default {
  20. data() {
  21. return {
  22. provinceData,
  23. cityData,
  24. cities: cityData[provinceData[0]],
  25. secondCity: cityData[provinceData[0]][0],
  26. };
  27. },
  28. methods: {
  29. handleProvinceChange(value) {
  30. this.cities = cityData[value];
  31. this.secondCity = cityData[value][0];
  32. },
  33. },
  34. };
  35. </script>

Select 选择器 - 图8

分组

OptGroup 进行选项分组。

  1. <template>
  2. <a-select defaultValue="lucy" style="width: 200px" @change="handleChange">
  3. <a-select-opt-group>
  4. <span slot="label"><a-icon type="user" />Manager</span>
  5. <a-select-option value="jack">Jack</a-select-option>
  6. <a-select-option value="lucy">Lucy</a-select-option>
  7. </a-select-opt-group>
  8. <a-select-opt-group label="Engineer">
  9. <a-select-option value="Yiminghe">yiminghe</a-select-option>
  10. </a-select-opt-group>
  11. </a-select>
  12. </template>
  13. <script>
  14. export default {
  15. methods: {
  16. handleChange(value) {
  17. console.log(`selected ${value}`);
  18. },
  19. },
  20. };
  21. </script>

Select 选择器 - 图9

搜索框

搜索和远程数据结合。

  1. <template>
  2. <a-select
  3. showSearch
  4. :value="value"
  5. placeholder="input search text"
  6. style="width: 200px"
  7. :defaultActiveFirstOption="false"
  8. :showArrow="false"
  9. :filterOption="false"
  10. @search="handleSearch"
  11. @change="handleChange"
  12. :notFoundContent="null"
  13. >
  14. <a-select-option v-for="d in data" :key="d.value">{{d.text}}</a-select-option>
  15. </a-select>
  16. </template>
  17. <script>
  18. import jsonp from 'fetch-jsonp';
  19. import querystring from 'querystring';
  20. let timeout;
  21. let currentValue;
  22. function fetch(value, callback) {
  23. if (timeout) {
  24. clearTimeout(timeout);
  25. timeout = null;
  26. }
  27. currentValue = value;
  28. function fake() {
  29. const str = querystring.encode({
  30. code: 'utf-8',
  31. q: value,
  32. });
  33. jsonp(`https://suggest.taobao.com/sug?${str}`)
  34. .then(response => response.json())
  35. .then(d => {
  36. if (currentValue === value) {
  37. const result = d.result;
  38. const data = [];
  39. result.forEach(r => {
  40. data.push({
  41. value: r[0],
  42. text: r[0],
  43. });
  44. });
  45. callback(data);
  46. }
  47. });
  48. }
  49. timeout = setTimeout(fake, 300);
  50. }
  51. export default {
  52. data() {
  53. return {
  54. data: [],
  55. value: undefined,
  56. };
  57. },
  58. methods: {
  59. handleSearch(value) {
  60. fetch(value, data => (this.data = data));
  61. },
  62. handleChange(value) {
  63. console.log(value);
  64. this.value = value;
  65. fetch(value, data => (this.data = data));
  66. },
  67. },
  68. };
  69. </script>

Select 选择器 - 图10

带搜索框

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

  1. <template>
  2. <a-select
  3. showSearch
  4. placeholder="Select a person"
  5. optionFilterProp="children"
  6. style="width: 200px"
  7. @focus="handleFocus"
  8. @blur="handleBlur"
  9. @change="handleChange"
  10. :filterOption="filterOption"
  11. >
  12. <a-select-option value="jack">Jack</a-select-option>
  13. <a-select-option value="lucy">Lucy</a-select-option>
  14. <a-select-option value="tom">Tom</a-select-option>
  15. </a-select>
  16. </template>
  17. <script>
  18. export default {
  19. methods: {
  20. handleChange(value) {
  21. console.log(`selected ${value}`);
  22. },
  23. handleBlur() {
  24. console.log('blur');
  25. },
  26. handleFocus() {
  27. console.log('focus');
  28. },
  29. filterOption(input, option) {
  30. return (
  31. option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
  32. );
  33. },
  34. },
  35. };
  36. </script>

Select 选择器 - 图11

搜索用户

一个带有远程搜索,节流控制,请求时序控制,加载状态的多选示例。

  1. <template>
  2. <a-select
  3. mode="multiple"
  4. labelInValue
  5. :value="value"
  6. placeholder="Select users"
  7. style="width: 100%"
  8. :filterOption="false"
  9. @search="fetchUser"
  10. @change="handleChange"
  11. :notFoundContent="fetching ? undefined : null"
  12. >
  13. <a-spin v-if="fetching" slot="notFoundContent" size="small" />
  14. <a-select-option v-for="d in data" :key="d.value">{{d.text}}</a-select-option>
  15. </a-select>
  16. </template>
  17. <script>
  18. import jsonp from 'fetch-jsonp';
  19. import querystring from 'querystring';
  20. import debounce from 'lodash/debounce';
  21. export default {
  22. data() {
  23. this.lastFetchId = 0;
  24. this.fetchUser = debounce(this.fetchUser, 800);
  25. return {
  26. data: [],
  27. value: [],
  28. fetching: false,
  29. };
  30. },
  31. methods: {
  32. fetchUser(value) {
  33. console.log('fetching user', value);
  34. this.lastFetchId += 1;
  35. const fetchId = this.lastFetchId;
  36. this.data = [];
  37. this.fetching = true;
  38. fetch('https://randomuser.me/api/?results=5')
  39. .then(response => response.json())
  40. .then(body => {
  41. if (fetchId !== this.lastFetchId) {
  42. // for fetch callback order
  43. return;
  44. }
  45. const data = body.results.map(user => ({
  46. text: `${user.name.first} ${user.name.last}`,
  47. value: user.login.username,
  48. }));
  49. this.data = data;
  50. this.fetching = false;
  51. });
  52. },
  53. handleChange(value) {
  54. Object.assign(this, {
  55. value,
  56. data: [],
  57. fetching: false,
  58. });
  59. },
  60. },
  61. };
  62. </script>

Select 选择器 - 图12

后缀图标

基本使用。

  1. <template>
  2. <div>
  3. <a-select defaultValue="lucy" style="width: 120px" @change="handleChange">
  4. <a-icon slot="suffixIcon" type="smile" />
  5. <a-select-option value="jack">Jack</a-select-option>
  6. <a-select-option value="lucy">Lucy</a-select-option>
  7. <a-select-option value="disabled" disabled>Disabled</a-select-option>
  8. <a-select-option value="Yiminghe">yiminghe</a-select-option>
  9. </a-select>
  10. <a-select defaultValue="lucy" style="width: 120px" disabled>
  11. <a-icon slot="suffixIcon" type="meh" />
  12. <a-select-option value="lucy">Lucy</a-select-option>
  13. </a-select>
  14. </div>
  15. </template>
  16. <script>
  17. export default {
  18. methods: {
  19. handleChange(value) {
  20. console.log(`selected ${value}`);
  21. },
  22. },
  23. };
  24. </script>

Select 选择器 - 图13

隐藏已选择选项

隐藏下拉列表中已选择的选项。

<template>
  <a-select
    mode="multiple"
    placeholder="Inserted are removed"
    :value="selectedItems"
    @change="handleChange"
    style="width: 100%"
  >
    <a-select-option v-for="item in filteredOptions" :key="item" :value="item">
      {{item}}
    </a-select-option>
  </a-select>
</template>
<script>
  const OPTIONS = ['Apples', 'Nails', 'Bananas', 'Helicopters'];
  export default {
    data() {
      return {
        selectedItems: [],
      };
    },
    computed: {
      filteredOptions() {
        return OPTIONS.filter(o => !this.selectedItems.includes(o));
      },
    },
    methods: {
      handleChange(selectedItems) {
        this.selectedItems = selectedItems;
      },
    },
  };
</script>

Select 选择器 - 图14

扩展菜单

使用 dropdownRender 对下拉菜单进行自由扩展。

<template>
  <a-select defaultValue="lucy" style="width: 120px">
    <div slot="dropdownRender" slot-scope="menu">
      <v-nodes :vnodes="menu" />
      <a-divider style="margin: 4px 0;" />
      <div style="padding: 8px; cursor: pointer;"><a-icon type="plus" /> Add item</div>
    </div>
    <a-select-option value="jack">Jack</a-select-option>
    <a-select-option value="lucy">Lucy</a-select-option>
  </a-select>
</template>
<script>
  export default {
    data: () => ({ console: console }),
    components: {
      VNodes: {
        functional: true,
        render: (h, ctx) => ctx.props.vnodes,
      },
    },
  };
</script>

API

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

Select props

参数说明类型默认值
allowClear支持清除booleanfalse
autoClearSearchValue是否在选中项后清空搜索框,只在 modemultipletags 时有效。booleantrue
autoFocus默认获取焦点booleanfalse
defaultActiveFirstOption是否默认高亮第一个选项。booleantrue
defaultValue指定默认选中的条目string|string[]|number|number[]-
disabled是否禁用booleanfalse
dropdownClassName下拉菜单的 className 属性string-
dropdownMatchSelectWidth下拉菜单和选择器同宽booleantrue
dropdownRender自定义下拉框内容(menuNode: VNode, props) => VNode-
dropdownStyle下拉菜单的 style 属性object-
filterOption是否根据输入项进行筛选。当其为一个函数时,会接收 inputValue option 两个参数,当 option 符合筛选条件时,应返回 true,反之则返回 falseboolean or function(inputValue, option)true
firstActiveValue默认高亮的选项string|string[]-
getPopupContainer菜单渲染父节点。默认渲染到 body 上,如果你遇到菜单滚动定位问题,试试修改为滚动的区域,并相对其定位。Function(triggerNode)() => document.body
labelInValue是否把每个选项的 label 包装到 value 中,会把 Select 的 value 类型从 string 变为 {key: string, label: vNodes} 的格式booleanfalse
maxTagCount最多显示多少个 tagnumber-
maxTagPlaceholder隐藏 tag 时显示的内容slot/function(omittedValues)-
maxTagTextLength最大显示的 tag 文本长度number-
mode设置 Select 的模式为多选或标签'default' | 'multiple' | 'tags' | 'combobox'-
notFoundContent当下拉列表为空时显示的内容string|slot'Not Found'
optionFilterProp搜索时过滤对应的 option 属性,如设置为 children 表示对内嵌内容进行搜索stringvalue
optionLabelProp回填到选择框的 Option 的属性值,默认是 Option 的子元素。比如在子元素需要高亮效果时,此值可以设为 valuestringchildren (combobox 模式下为 value
placeholder选择框默认文字string|slot-
showSearch使单选模式可搜索booleanfalse
showArrow是否显示下拉小箭头booleantrue
size选择框大小,可选 large smallstringdefault
suffixIcon自定义的选择框后缀图标VNode | slot-
removeIcon自定义的多选框清除图标VNode | slot-
clearIcon自定义的多选框清空图标VNode | slot-
menuItemSelectedIcon自定义当前选中的条目图标VNode | slot-
tokenSeparators在 tags 和 multiple 模式下自动分词的分隔符string[]
value(v-model)指定当前选中的条目string|string[]|number|number[]-
optionsoptions 数据,如果设置则不需要手动构造 selectOption 节点array<{value, label, [disabled, key, title]}>[]
defaultOpen是否默认展开下拉菜单boolean-
open是否展开下拉菜单boolean-

注意,如果发现下拉菜单跟随页面滚动,或者需要在其他弹层中触发 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)
focus获得焦点时回调function
inputKeydown键盘按下时回调function
mouseenter鼠标移入时回调function
mouseleave鼠标移出时回调function
popupScroll下拉列表滚动时的回调function
search文本框值变化时回调function(value: string)
select被选中时调用,参数为选中项的 value (或 key) 值function(value, option:Option)
dropdownVisibleChange展开下拉菜单的回调function(open)

Select Methods

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

Option props

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

OptGroup props

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