Skip to content

AutoComplete 自动完成

输入框自动完成功能。

代码演示

基础用法

基本使用。通过 options 设置自动完成的数据源。

vue
<template>
  <a-auto-complete
    v-model:value="value"
    :options="options"
    style="width: 200px"
    placeholder="input here"
    @select="onSelect"
    @search="onSearch"
  />
</template>
<script setup>
import { ref, watch } from 'vue';
const mockVal = (str, repeat = 1) => {
  return {
    value: str.repeat(repeat),
  };
};
const value = ref('');
const options = ref([]);
const onSearch = searchText => {
  console.log('searchText');
  options.value = !searchText
    ? []
    : [mockVal(searchText), mockVal(searchText, 2), mockVal(searchText, 3)];
};
const onSelect = value => {
  console.log('onSelect', value);
};
watch(value, () => {
  console.log('value', value.value);
});
</script>

自定义选项

可以传递 v-slot:option 来自定义 Option。

vue
<template>
  <a-auto-complete
    v-model:value="value"
    style="width: 200px"
    placeholder="input here"
    :options="options"
    @search="handleSearch"
  >
    <template #option="{ value: val }">
      {{ val.split('@')[0] }} @
      <span style="font-weight: bold">{{ val.split('@')[1] }}</span>
    </template>
  </a-auto-complete>
</template>
<script setup>
import { ref } from 'vue';
const value = ref('');
const options = ref([]);
const handleSearch = val => {
  let res;
  if (!val || val.indexOf('@') >= 0) {
    res = [];
  } else {
    res = ['gmail.com', '163.com', 'qq.com'].map(domain => ({
      value: `${val}@${domain}`,
    }));
  }
  options.value = res;
};
</script>

自定义输入组件

vue
<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 setup>
import { ref } from 'vue';
const value = ref('');
const options = ref([]);
const onSelect = value => {
  console.log('onSelect', value);
};
const handleSearch = value => {
  options.value = !value
    ? []
    : [
        {
          value,
        },
        {
          value: value + value,
        },
        {
          value: value + value + value,
        },
      ];
};
const handleKeyPress = ev => {
  console.log('handleKeyPress', ev);
};
</script>

查询模式 - 确定类目

vue
<template>
  <div class="certain-category-search-wrapper" style="width: 250px">
    <a-auto-complete
      v-model:value="value"
      class="certain-category-search"
      popup-class-name="certain-category-search-dropdown"
      :dropdown-match-select-width="500"
      style="width: 250px"
      :options="dataSource"
    >
      <template #option="item">
        <template v-if="item.options">
          <span>
            {{ item.value }}
            <a
              style="float: right"
              href="https://www.google.com/search?q=antd"
              target="_blank"
              rel="noopener noreferrer"
            >
              more
            </a>
          </span>
        </template>
        <template v-else-if="item.value === 'all'">
          <a
            href="https://www.google.com/search?q=ant-design-vue"
            target="_blank"
            rel="noopener noreferrer"
          >
            View all results
          </a>
        </template>
        <template v-else>
          <div style="display: flex; justify-content: space-between">
            {{ item.value }}
            <span>
              <UserOutlined />
              {{ item.count }}
            </span>
          </div>
        </template>
      </template>
      <a-input-search placeholder="input here" size="large"></a-input-search>
    </a-auto-complete>
  </div>
</template>
<script setup>
import { ref } from 'vue';
const dataSource = [
  {
    value: 'Libraries',
    options: [
      {
        value: 'AntDesignVue',
        count: 10000,
      },
      {
        value: 'AntDesignVue UI',
        count: 10600,
      },
    ],
  },
  {
    value: 'Solutions',
    options: [
      {
        value: 'AntDesignVue UI FAQ',
        count: 60100,
      },
      {
        value: 'AntDesignVue FAQ',
        count: 30010,
      },
    ],
  },
  {
    value: 'Articles',
    options: [
      {
        value: 'AntDesignVue design language',
        count: 100000,
      },
    ],
  },
  {
    value: 'all',
  },
];
const value = ref('');
</script>
<style scoped>
.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>

自定义状态

使用 statusAutoComplete 添加状态,可选 error 或者 warning

vue
<template>
  <a-space direction="vertical" style="width: 100%">
    <a-auto-complete
      v-model:value="value"
      :options="options"
      style="width: 200px"
      placeholder="input here"
      status="error"
      @select="onSelect"
      @search="onSearch"
    />
    <a-auto-complete
      v-model:value="value1"
      :options="options"
      style="width: 200px"
      placeholder="input here"
      status="warning"
      allow-clear
      @select="onSelect"
      @search="onSearch"
      @clear="onClear"
    />
  </a-space>
</template>
<script setup>
import { ref, watch } from 'vue';
const mockVal = (str, repeat = 1) => {
  return {
    value: str.repeat(repeat),
  };
};
const value = ref('');
const value1 = ref('');
const options = ref([]);
const onSearch = searchText => {
  console.log('searchText');
  options.value = !searchText
    ? []
    : [mockVal(searchText), mockVal(searchText, 2), mockVal(searchText, 3)];
};
const onSelect = value => {
  console.log('onSelect', value);
};
const onClear = () => {
  console.log('onClear');
};
watch(value, () => {
  console.log('value', value.value);
});
</script>

API

html
<a-auto-complete v-model:value="value" :options="options" />
参数说明类型默认值
allowClear支持清除, 单选模式有效booleanfalse
autofocus自动获取焦点booleanfalse
backfill使用键盘选择选项的时候把选中项回填到输入框中booleanfalse
bordered是否有边框booleantrue
clearIcon使用插槽自定义清除按钮slot
default (自定义输入框)自定义输入框slot
defaultActiveFirstOption是否默认高亮第一个选项。booleantrue
defaultOpen是否默认展开下拉菜单boolean-
disabled是否禁用booleanfalse
popupClassName下拉菜单的 className 属性string-
dropdownMatchSelectWidth下拉菜单和选择器同宽。默认将设置 min-width,当值小于选择框宽度时会被忽略。false 时会关闭虚拟滚动boolean | numbertrue
dropdownMenuStyledropdown 菜单自定义样式object
filterOption是否根据输入项进行筛选。当其为一个函数时,会接收 inputValue option 两个参数,当 option 符合筛选条件时,应返回 true,反之则返回 false。boolean or function (inputValue, option)true
open是否展开下拉菜单boolean-
option通过 option 插槽,自定义节点v-slot:option="{value, label, [disabled, key, title]}"-
options自动完成的数据源DataSourceItemType[]
placeholder输入框提示string | slot-
status设置校验状态'error' | 'warning'-
v-model:value指定当前选中的条目string | string[] | { key: string, label: string | vNodes } | Array<{ key: string, label: string | vNodes }>

事件

事件名称说明回调参数
blur失去焦点时的回调function()
change选中 option,或 input 的 value 变化时,调用此函数function(value)
dropdownVisibleChange展开下拉菜单的回调function(open)
focus获得焦点时的回调function()
search搜索补全项的时候调用function(value)
select被选中时调用,参数为选中项的 value 值function(value, option)
clear清除内容时回调function

方法

名称描述版本
blur()移除焦点
focus()获取焦点