AutoComplete 自动完成
输入框自动完成功能。
何时使用
- 需要一个输入框而不是选择器。
- 需要输入建议/辅助提示。
和 Select 的区别是:
- AutoComplete 是一个带提示的文本输入框,用户可以自由输入,关键词是辅助输入。
- Select 是在限定的可选项中进行选择,关键词是选择。
代码演示
基本使用。通过 options 设置自动完成的数据源。
<template>
<a-auto-complete
v-model:value="value"
:options="options"
style="width: 200px"
placeholder="input here"
@select="onSelect"
@search="onSearch"
/>
</template>
<script lang="ts">
import { defineComponent, ref, watch } from 'vue';
interface MockVal {
value: string;
}
const mockVal = (str: string, repeat = 1): MockVal => {
return {
value: str.repeat(repeat),
};
};
export default defineComponent({
setup() {
const value = ref('');
const options = ref<MockVal[]>([]);
const onSearch = (searchText: string) => {
console.log('searchText');
options.value = !searchText
? []
: [mockVal(searchText), mockVal(searchText, 2), mockVal(searchText, 3)];
};
const onSelect = (value: string) => {
console.log('onSelect', value);
};
watch(value, () => {
console.log('value', value.value);
});
return {
value,
options,
onSearch,
onSelect,
};
},
});
</script>
自定义输入组件。
<template>
<a-auto-complete
v-model:value="value"
:options="options"
style="width: 200px"
@search="handleSearch"
@select="onSelect"
>
<a-textarea
placeholder="input here"
class="custom"
style="height: 50px"
@keypress="handleKeyPress"
/>
</a-auto-complete>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue';
export default defineComponent({
setup() {
const value = ref('');
const options = ref<{ value: string }[]>([]);
const onSelect = (value: string) => {
console.log('onSelect', value);
};
const handleSearch = (value: string) => {
options.value = !value
? []
: [{ value }, { value: value + value }, { value: value + value + value }];
};
const handleKeyPress = (ev: KeyboardEvent) => {
console.log('handleKeyPress', ev);
};
return {
value,
options,
onSelect,
handleSearch,
handleKeyPress,
};
},
});
</script>
查询模式 - 确定类目。
<template>
<div class="certain-category-search-wrapper" style="width: 250px">
<a-auto-complete
v-model:value="value"
class="certain-category-search"
dropdown-class-name="certain-category-search-dropdown"
:dropdown-match-select-width="false"
:dropdown-style="{ width: '300px' }"
size="large"
style="width: 100%"
placeholder="input here"
option-label-prop="value"
>
<template #dataSource>
<a-select-opt-group v-for="group in dataSource" :key="group.title">
<template #label>
<span>
{{ group.title }}
<a
style="float: right"
href="https://www.google.com/search?q=antd"
target="_blank"
rel="noopener noreferrer"
>
more
</a>
</span>
</template>
<a-select-option v-for="opt in group.children" :key="opt.title" :value="opt.title">
{{ opt.title }}
<span class="certain-search-item-count">{{ opt.count }} people</span>
</a-select-option>
</a-select-opt-group>
<a-select-option key="all" disabled class="show-all">
<a
href="https://www.google.com/search?q=ant-design-vue"
target="_blank"
rel="noopener noreferrer"
>
View all results
</a>
</a-select-option>
</template>
<a-input>
<template #suffix><search-outlined class="certain-category-icon" /></template>
</a-input>
</a-auto-complete>
</div>
</template>
<script lang="ts">
import { SearchOutlined } from '@ant-design/icons-vue';
import { defineComponent, ref } from 'vue';
const dataSource = [
{
title: 'Libraries',
children: [
{
title: 'AntDesign',
count: 10000,
},
{
title: 'AntDesign UI',
count: 10600,
},
],
},
{
title: 'Solutions',
children: [
{
title: 'AntDesign UI FAQ',
count: 60100,
},
{
title: 'AntDesign FAQ',
count: 30010,
},
],
},
{
title: 'Articles',
children: [
{
title: 'AntDesign design language',
count: 100000,
},
],
},
];
export default defineComponent({
setup() {
return {
value: ref(''),
dataSource,
};
},
components: {
SearchOutlined,
},
});
</script>
<style>
.certain-category-search-dropdown .ant-select-dropdown-menu-item-group-title {
color: #666;
font-weight: bold;
}
.certain-category-search-dropdown .ant-select-dropdown-menu-item-group {
border-bottom: 1px solid #f6f6f6;
}
.certain-category-search-dropdown .ant-select-dropdown-menu-item {
padding-left: 16px;
}
.certain-category-search-dropdown .ant-select-dropdown-menu-item.show-all {
text-align: center;
cursor: default;
}
.certain-category-search-dropdown .ant-select-dropdown-menu {
max-height: 300px;
}
</style>
<style scoped>
.certain-category-search-wrapper
:deep(.certain-category-search.ant-select-auto-complete)
.ant-input-affix-wrapper
.ant-input-suffix {
right: 12px;
}
.certain-category-search-wrapper :deep(.certain-search-item-count) {
position: absolute;
color: #999;
right: 16px;
}
.certain-category-search-wrapper
:deep(.certain-category-search.ant-select-focused)
.certain-category-icon {
color: #108ee9;
}
.certain-category-search-wrapper :deep(.certain-category-icon) {
color: #6e6e6e;
transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
font-size: 16px;
}
</style>
也可以直接传递 #dataSource 的Option。
<template>
<a-auto-complete
v-model:value="value"
style="width: 200px"
placeholder="input here"
@search="handleSearch"
>
<template #dataSource>
<a-select-option v-for="email in result" :key="email">
{{ email }}
</a-select-option>
</template>
</a-auto-complete>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue';
export default defineComponent({
setup() {
const value = ref('');
const result = ref<string[]>([]);
const handleSearch = (val: string) => {
let res: string[];
if (!val || val.indexOf('@') >= 0) {
res = [];
} else {
res = ['gmail.com', '163.com', 'qq.com'].map(domain => `${val}@${domain}`);
}
result.value = res;
};
return {
value,
result,
handleSearch,
};
},
});
</script>
不区分大小写的 AutoComplete。
<template>
<a-auto-complete
v-model:value="value"
:options="options"
style="width: 200px"
placeholder="input here"
:filter-option="filterOption"
/>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue';
interface Option {
value: string;
}
export default defineComponent({
setup() {
const filterOption = (input: string, option: Option) => {
return option.value.toUpperCase().indexOf(input.toUpperCase()) >= 0;
};
return {
value: ref(''),
options: ref<Option[]>([
{ value: 'Burns Bay Road' },
{ value: 'Downing Street' },
{ value: 'Wall Street' },
]),
filterOption,
};
},
});
</script>
查询模式 - 不确定类目。
<template>
<div class="global-search-wrapper" style="width: 300px">
<a-auto-complete
v-model:value="value"
class="global-search"
size="large"
style="width: 100%"
option-label-prop="title"
@select="onSelect"
@search="handleSearch"
>
<template #dataSource>
<a-select-option v-for="item in dataSource" :key="item.category" :title="item.category">
Found {{ item.query }} on
<a
:href="`https://s.taobao.com/search?q=${item.query}`"
target="_blank"
rel="noopener noreferrer"
>
{{ item.category }}
</a>
<span class="global-search-item-count">{{ item.count }} results</span>
</a-select-option>
</template>
<a-input-search size="large" placeholder="input here" enterButton></a-input-search>
</a-auto-complete>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue';
interface Option {
query: string;
category: string;
count: number;
}
export default defineComponent({
setup() {
const value = ref('');
const dataSource = ref<Option[]>([]);
const onSelect = (value: string) => {
console.log('onSelect', value);
};
const getRandomInt = (max: number, min = 0) => {
return Math.floor(Math.random() * (max - min + 1)) + min;
};
const searchResult = (query: string): Option[] => {
return new Array(getRandomInt(5))
.join('.')
.split('.')
.map((item, idx) => ({
query,
category: `${query}${idx}`,
count: getRandomInt(200, 100),
}));
};
const handleSearch = (val: string) => {
dataSource.value = val ? searchResult(val) : [];
};
return {
value,
dataSource,
onSelect,
handleSearch,
};
},
});
</script>
<style>
.global-search-wrapper {
padding-right: 50px;
}
.global-search {
width: 100%;
}
.global-search.ant-select-auto-complete .ant-select-selection--single {
margin-right: -46px;
}
.global-search.ant-select-auto-complete .ant-input-affix-wrapper .ant-input:not(:last-child) {
padding-right: 62px;
}
.global-search.ant-select-auto-complete .ant-input-affix-wrapper .ant-input-suffix button {
border-top-left-radius: 0;
border-bottom-left-radius: 0;
}
.global-search-item {
display: flex;
}
.global-search-item-desc {
flex: auto;
text-overflow: ellipsis;
overflow: hidden;
}
.global-search-item-count {
flex: none;
}
</style>
API
<a-auto-complete v-model:value="value" :options="options" />
参数 | 说明 | 类型 | 默认值 | 版本 |
---|---|---|---|---|
allowClear | 支持清除, 单选模式有效 | boolean | false | |
autofocus | 自动获取焦点 | boolean | false | |
backfill | 使用键盘选择选项的时候把选中项回填到输入框中 | boolean | false | |
#default (自定义输入框) | 自定义输入框 | HTMLInputElement / HTMLTextAreaElement | <Input /> | |
options | 自动完成的数据源 | slot | DataSourceItemType[] | ||
dropdownMenuStyle | dropdown 菜单自定义样式 | object | 1.5.0 | |
defaultActiveFirstOption | 是否默认高亮第一个选项。 | boolean | true | |
disabled | 是否禁用 | boolean | false | |
filterOption | 是否根据输入项进行筛选。当其为一个函数时,会接收 inputValue option 两个参数,当 option 符合筛选条件时,应返回 true ,反之则返回 false 。 | boolean or function(inputValue, option) | true | |
optionLabelProp | 回填到选择框的 Option 的属性值,默认是 Option 的子元素。比如在子元素需要高亮效果时,此值可以设为 value 。 | string | children | |
placeholder | 输入框提示 | string | slot | - | |
v-model:value | 指定当前选中的条目 | string|string[]|{ key: string, label: string|vNodes }|Array<{ key: string, label: string|vNodes }> | 无 | |
defaultOpen | 是否默认展开下拉菜单 | boolean | - | |
open | 是否展开下拉菜单 | boolean | - |
事件
事件名称 | 说明 | 回调参数 | 版本 |
---|---|---|---|
change | 选中 option,或 input 的 value 变化时,调用此函数 | function(value) | |
blur | 失去焦点时的回调 | function() | |
focus | 获得焦点时的回调 | function() | |
search | 搜索补全项的时候调用 | function(value) | |
select | 被选中时调用,参数为选中项的 value 值 | function(value, option) | |
dropdownVisibleChange | 展开下拉菜单的回调 | function(open) |
方法
名称 | 描述 | 版本 |
---|---|---|
blur() | 移除焦点 | |
focus() | 获取焦点 |