---
title: "MazInputAutocomplete"
description: "MazInputAutocomplete is a text input suggesting values while typing, from a local list (fuzzy search with typo tolerance) or from an async source (an API), with keyboard navigation, highlight of the matches and the ARIA combobox pattern."
package: "maz-ui"
url: "https://maz-ui.com/components/maz-input-autocomplete"
---

# MazInputAutocomplete

> MazInputAutocomplete is a text input suggesting values while typing, from a local list (fuzzy search with typo tolerance) or from an async source (an API), with keyboard navigation, highlight of the matches and the ARIA combobox pattern.

- Package: `maz-ui`
- Import: `import MazInputAutocomplete from 'maz-ui/components/MazInputAutocomplete'`
- Nuxt: auto-imported by `@maz-ui/nuxt`, no import needed in a Nuxt app
- Web: https://maz-ui.com/components/maz-input-autocomplete

> Before use it, you should install the MazUi plugin in your project, follow instructions in [Getting Started](../guide/getting-started.md)

Unlike `MazSelect`, the value is the text typed: a suggestion fills the input, and any other text stays allowed. `v-model:selected` gives the chosen suggestion (`undefined` once the text is edited).

## Basic usage

The `items` are searched with [fuzzySearch](https://maz-ui.com/ecosystem/utils/fuzzy-search.md): prefixes, words in any order, initials ("nwz"), typos ("Franse"), accents and case. The best matches come first, the matched characters are highlighted.

```vue
<script lang="ts" setup>
import MazInputAutocomplete from 'maz-ui/components/MazInputAutocomplete'
import { useDisplayNames } from 'maz-ui/composables/useDisplayNames'
import { ref } from 'vue'

interface Country {
  label: string
  value: string
}

const countries: Country[] = useDisplayNames('en-US')
  .getAllDisplayNames({ type: 'region' })
  .value
  .map(({ code, name }) => ({ label: name, value: code }))

const country = ref('')
const selectedCountry = ref<Country>()
</script>

<template>
  <MazInputAutocomplete
    v-model="country"
    v-model:selected="selectedCountry"
    label="Country"
    :items="countries"
    :limit="8"
    block
  />
</template>
```

## Items

The `items` can be strings, numbers or objects. For objects, `item-label` gives the text (key or function, default `label`) and `item-value` the identity used to find the selected suggestion (default `value`).

`search-keys` changes the searched keys, with their weight (default: the label).

```vue
<MazInputAutocomplete
  v-model="user"
  label="User"
  :items="users"
  :item-label="user => `${user.firstName} ${user.lastName}`"
  item-value="id"
  :search-keys="[
    user => `${user.firstName} ${user.lastName}`,
    { key: 'email', weight: 0.6 },
  ]"
/>
```

`search-threshold` is the tolerance to typos: the minimal similarity (from 0 to 1) of a whole value with the query. `1` disables it (default `0.75`).

## Async source

`source` loads the suggestions of a query: an API, a database. It is called after `debounce` ms (default `300`), with an `AbortSignal` aborted when a new query is typed, and its results are displayed in their order (the matched characters are still highlighted). The input shows a loader meanwhile.

```vue
<script lang="ts" setup>
import type { MazInputAutocompleteSourceContext } from 'maz-ui/components/MazInputAutocomplete'
import MazInputAutocomplete from 'maz-ui/components/MazInputAutocomplete'
import { ref } from 'vue'

interface City {
  label: string
  value: string
  country: string
}

const city = ref('')

async function searchCities(query: string, { signal }: MazInputAutocompleteSourceContext) {
  const response = await fetch(`/api/cities?q=${encodeURIComponent(query)}`, { signal })

  return response.json() as Promise<City[]>
}
</script>

<template>
  <MazInputAutocomplete
    v-model="city"
    label="City"
    :source="searchCities"
    :min-chars="2"
    block
  >
    <template #item="{ item, segments }">
      <span class="flex w-full items-center justify-between gap-2">
        <span>
          <template v-for="(segment, index) in segments" :key="index">
            <b v-if="segment.match">{{ segment.text }}</b>
            <template v-else>{{ segment.text }}</template>
          </template>
        </span>
        <span class="text-muted">{{ item.country }}</span>
      </span>
    </template>
  </MazInputAutocomplete>
</template>
```

When the `source` throws, the `error` slot (with a `retry` function) is displayed and the `error` event is emitted.

## Open on focus

`open-on-focus` opens the suggestions on focus. With `min-chars` at `0`, every item is listed before typing (or the `source` is called with an empty query).

```vue
<MazInputAutocomplete
  v-model="fruit"
  label="Fruit"
  :items="['Apple', 'Apricot', 'Banana', 'Cherry', 'Grape', 'Kiwi', 'Mango', 'Orange', 'Peach', 'Pear']"
  :min-chars="0"
  open-on-focus
/>
```

## Accessibility

The input is a [combobox](https://www.w3.org/WAI/ARIA/apg/patterns/combobox/) (`aria-autocomplete="list"`): the focus stays in it, `aria-activedescendant` points to the active suggestion, and the number of results is announced to the screen readers.

| Key                    | Action                                                       |
| ---------------------- | ------------------------------------------------------------ |
| `ArrowDown`, `ArrowUp` | Open the list, move the active suggestion (`Alt` only opens) |
| `Enter`                | Choose the active suggestion, or the first one               |
| `Escape`               | Close the list, a second time clear the input                |
| `Tab`                  | Close the list and move the focus                            |

**Tip:**

This component can be translated globally using the [MazUi](https://maz-ui.com/ecosystem/translations.md) plugin.

## MazInputAutocomplete API

`import MazInputAutocomplete from 'maz-ui/components/MazInputAutocomplete'`

### Props

- `id` (`string`): The id of the input.
- `model-value` (`string`, default: `""`, `v-model`): The text of the input.
- `selected` (`T`, `v-model:selected`): The chosen suggestion, `undefined` once the text is edited.
- `items` (`T[]`): The suggestions searched locally (fuzzy search: prefixes, words in any order, scattered letters, typos, accents).
- `source` (`((query: string, context: MazInputAutocompleteSourceContext) => T[] | Promise<T[]>)`): Load the suggestions of a query (an API...): they are displayed as they are, in their order. The previous request is aborted with the `signal` when a new query is typed.
- `item-label` (`string | ((item: T) => string)`, default: `"label"`): The key or the function giving the text of a suggestion (displayed in the list and in the input once chosen).
- `item-value` (`string | ((item: T) => unknown)`, default: `"value"`): The key or the function giving the identity of a suggestion (to find the selected one).
- `search-keys` (`FuzzySearchKey<T>[]`, default: `the label of the items`): The keys searched in the `items`, with their weight (see `fuzzySearch` of `@maz-ui/utils`).
- `search-threshold` (`number`, default: `0.75`): Tolerance of the search in the `items` to typos: the minimal similarity (from 0 to 1) of a whole value with the query. `1` disables the typo tolerance.
- `min-chars` (`number`, default: `1`): Minimal number of characters typed to search.
- `debounce` (`number`, default: `300`): Delay in ms between the last character typed and the call of the `source`.
- `limit` (`number`): Maximum number of suggestions displayed.
- `highlight` (`boolean`, default: `true`): Highlight the characters matching the query in the suggestions.
- `open-on-focus` (`boolean`, default: `false`): Open the suggestions on focus, with `min-chars` at `0` it lists every item.
- `label` (`string`): The label of the input.
- `top-label` (`string`): Static label displayed above the input.
- `placeholder` (`string`): The placeholder of the input.
- `size` (`"xs" | "sm" | "md" | "lg" | "xl" | "mini"`, default: `'md'`): The size of the input.
- `color` (`"primary" | "secondary" | "accent" | "info" | "success" | "warning" | "destructive" | "contrast" | "transparent"`, default: `"primary"`): The color of the input and of the selected suggestion.
- `disabled` (`boolean`): Disable the component.
- `block` (`boolean`): The input will be displayed in full width.
- `max-list-height` (`number`, default: `240`): The max height of the list.
- `list-position` (`MazPopoverPosition`, default: `"auto"`): The position of the list.
- `transition` (`string`, default: `"scale-fade"`): The transition of the list.
- `translations` (`Partial<{ noResults: string; loading: string; error: string; results: string; }>`, default: `{ noResults: 'No results', loading: 'Loading...', error: 'An error occurred, try again', results: 'Results: {count}' }`): The translations of the component.

### Events

- `@open`: The list is opened
- `@error` (payload: `error: unknown`): The `source` failed
- `@close`: The list is closed
- `@select` (payload: `item: T`): A suggestion is chosen
- `@blur` (payload: `event: Event`): The input is blurred
- `@focus` (payload: `event: Event`): The input is focused
- `@update:modelValue` (payload: `value: string`)
- `@update:selected` (payload: `value: T | undefined`)

### Slots

- `#item`: A suggestion Bindings: `item: T`, `index: number`, `isActive: boolean`, `isSelected: boolean`, `segments: FuzzySearchSegment[]`.
- `#empty`: No suggestion for the query Bindings: `query: string`.
- `#loading`: The `source` is loading
- `#error`: The `source` failed Bindings: `error: unknown`, `retry: () => void`.
- `#header`: Content above the suggestions
- `#footer`: Content below the suggestions
- `#start-icon`: Content of the inline-start edge of the input
- `#end-icon`: Content of the inline-end edge of the input
