Select选择器
Select 选择器
下拉选择器。
何时使用
-
弹出一个下拉菜单给用户选择操作,用于代替原生的选择器,或者需要一个更优雅的多选器时。
-
当选项少时(少于 5 项),建议直接将选项平铺,使用 Radio 是更好的选择。
代码演示
基本使用
基本使用。
<template> <a-select v-model:value="value1" style="width: 120px" @focus="focus" ref="select" @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></template><script lang="ts">import { defineComponent, ref } from 'vue';export default defineComponent({ setup() { const focus = () => { console.log('focus'); }; const handleChange = (value: string) => { console.log(`selected ${value}`); }; return { focus, handleChange, value1: ref('lucy'), value2: ref('lucy'), value3: ref('lucy'), }; },});</script>
标签
tags select,随意输入的内容(scroll the menu)
<template> <a-select v-model:value="value" mode="tags" style="width: 100%" placeholder="Tags Mode" @change="handleChange" > <a-select-option v-for="i in 25" :key="(i + 9).toString(36) + i"> {{ (i + 9).toString(36) + i }} </a-select-option> </a-select></template><script lang="ts">import { defineComponent, ref } from 'vue';export default defineComponent({ setup() { const handleChange = (value: string) => { console.log(`selected ${value}`); }; return { value: ref([]), handleChange, }; },});</script>
获得选项的文本
默认情况下 onChange 里只能拿到 value,如果需要拿到选中的节点文本 label,可以使用 labelInValue 属性。 选中项的 label 会被包装到 value 中传递给 onChange 等函数,此时 value 是一个对象。
<template> <a-select label-in-value v-model:value="value" style="width: 120px" @change="handleChange"> <a-select-option value="jack">Jack (100)</a-select-option> <a-select-option value="lucy">Lucy (101)</a-select-option> </a-select></template><script lang="ts">import { defineComponent, ref } from 'vue';interface Value { key?: string; label?: string;}export default defineComponent({ setup() { const handleChange = (value: Value) => { console.log(value); // { key: "lucy", label: "Lucy (101)" } }; return { value: ref<Value>({ key: 'lucy' }), handleChange, }; },});</script>
联动
省市联动是典型的例子。 推荐使用 Cascader 组件。
<template> <a-select v-model:value="province" style="width: 120px"> <a-select-option v-for="pro in provinceData" :key="pro"> {{ pro }} </a-select-option> </a-select> <a-select v-model:value="secondCity" style="width: 120px"> <a-select-option v-for="city in cities" :key="city"> {{ city }} </a-select-option> </a-select></template><script lang="ts">const provinceData = ['Zhejiang', 'Jiangsu'];const cityData: Record<string, string[]> = { Zhejiang: ['Hangzhou', 'Ningbo', 'Wenzhou'], Jiangsu: ['Nanjing', 'Suzhou', 'Zhenjiang'],};import { defineComponent, reactive, toRefs, computed, watch } from 'vue';export default defineComponent({ setup() { const province = provinceData[0]; const state = reactive({ province, provinceData, cityData, secondCity: cityData[province][0], }); const cities = computed(() => { return cityData[state.province]; }); watch( () => state.province, val => { state.secondCity = state.cityData[val][0]; }, ); return { ...toRefs(state), cities, }; },});</script>
搜索框
搜索和远程数据结合。
<template> <a-select show-search v-model:value="value" placeholder="input search text" style="width: 200px" :default-active-first-option="false" :show-arrow="false" :filter-option="false" :not-found-content="null" @search="handleSearch" @change="handleChange" > <a-select-option v-for="d in data" :key="d.value"> {{ d.text }} </a-select-option> </a-select></template><script lang="ts">import jsonp from 'fetch-jsonp';import querystring from 'querystring';import { defineComponent, ref } from 'vue';let timeout: any;let currentValue = '';function fetch(value: string, callback: any) { if (timeout) { clearTimeout(timeout); timeout = null; } currentValue = value; function fake() { const str = querystring.encode({ code: 'utf-8', q: value, }); jsonp(`https://suggest.taobao.com/sug?${str}`) .then(response => response.json()) .then(d => { if (currentValue === value) { const result = d.result; const data: any[] = []; result.forEach((r: any) => { data.push({ value: r[0], text: r[0], }); }); callback(data); } }); } timeout = setTimeout(fake, 300);}export default defineComponent({ setup() { const data = ref<any[]>([]); const value = ref(); const handleSearch = (val: string) => { fetch(val, (d: any[]) => (data.value = d)); }; const handleChange = (val: string) => { console.log(val); value.value = val; fetch(val, (d: any[]) => (data.value = d)); }; return { handleSearch, handleChange, data, value, }; },});</script>
搜索用户
一个带有远程搜索,节流控制,请求时序控制,加载状态的多选示例。
<template> <a-select mode="multiple" label-in-value v-model:value="value" placeholder="Select users" style="width: 100%" :filter-option="false" :not-found-content="fetching ? undefined : null" @search="fetchUser" > <template v-if="fetching" #notFoundContent> <a-spin size="small" /> </template> <a-select-option v-for="d in data" :key="d.value"> {{ d.text }} </a-select-option> </a-select></template><script>import { defineComponent, reactive, toRefs, watch } from 'vue';import { debounce } from 'lodash-es';export default defineComponent({ setup() { let lastFetchId = 0; const state = reactive({ data: [], value: [], fetching: false, }); const fetchUser = debounce(value => { console.log('fetching user', value); lastFetchId += 1; const fetchId = lastFetchId; state.data = []; state.fetching = true; fetch('https://randomuser.me/api/?results=5') .then(response => response.json()) .then(body => { if (fetchId !== lastFetchId) { // for fetch callback order return; } const data = body.results.map(user => ({ text: `${user.name.first} ${user.name.last}`, value: user.login.username, })); state.data = data; state.fetching = false; }); }, 800); watch(state.value, () => { state.data = []; state.fetching = false; }); return { ...toRefs(state), fetchUser, }; },});</script>
隐藏已选择选项
隐藏下拉列表中已选择的选项。
<template> <a-select mode="multiple" placeholder="Inserted are removed" v-model:value="selectedItems" style="width: 100%" > <a-select-option v-for="item in filteredOptions" :key="item" :value="item"> {{ item }} </a-select-option> </a-select></template><script lang="ts">import { computed, defineComponent, ref } from 'vue';const OPTIONS = ['Apples', 'Nails', 'Bananas', 'Helicopters'];export default defineComponent({ setup() { const selectedItems = ref<string[]>([]); const filteredOptions = computed(() => OPTIONS.filter(o => !selectedItems.value.includes(o))); return { selectedItems, filteredOptions, }; },});</script>
定制回填内容
使用 optionLabelProp 指定回填到选择框的 Option 属性。
