본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

Vue AutoComplete 컴포넌트

원문 보기 위키 갱신

AutoComplete는 입력란에 글자를 타이핑하는 순간 실시간으로 추천 목록을 보여 주는 입력 컴포넌트예요. 검색창이나 태그 선택처럼 "사용자가 원하는 값을 미리 제안해 주고 싶을 때" 쓰는 컴포넌트라고 생각하면 쉬워요.

출처: primevue-components-autocomplete

본문

가져오기 (Import)

AutoComplete는 별도 설치 없이 PrimeVue에서 바로 가져와 쓸 수 있어요.

import AutoComplete from 'primevue/autocomplete';

접근성 (Accessibility)

스크린 리더

컴포넌트를 설명하는 값을 제공하려면 두 가지 방법 중 하나를 쓰면 돼요. inputId prop과 함께 label 태그를 연결하거나, 아니면 aria-labelledby, aria-label props를 직접 쓰는 방식이에요. 입력 엘리먼트에는 combobox role이 붙고, 여기에 aria-autocomplete, aria-haspopup, aria-expanded 속성이 함께 들어가요.

입력과 팝업 사이의 관계는 aria-controls로 만들고, 팝업 목록 안에서 키보드로 이동할 때 스크린 리더가 어떤 옵션을 읽어야 하는지는 aria-activedescendant 속성으로 알려 줘요. 여러 값을 고르는 multiple 모드에서는 칩(chip) 목록이 listbox role을 쓰되 aria-orientation이 horizontal로 잡히고, 각 칩은 option role에 자기 라벨이 aria-label로 들어가요. 팝업 목록은 입력 엘리먼트의 aria-controls가 가리키는 id를 갖고 있고 역할은 listbox예요. 목록의 각 항목은 option role과 id를 갖는데, 이 id가 입력 엘리먼트의 aria-activedescendant와 맞물리는 구조죠.

닫힌 상태 키보드 지원

키 동작
tab AutoComplete 엘리먼트로 포커스를 옮겨요.
출력 가능한 아무 문자 팝업을 열고 첫 번째 옵션으로 포커스를 옮겨요.

팝업 키보드 지원

키 동작
tab 팝업 안의 다음 포커스 가능한 엘리먼트로 포커스를 옮겨요. 더 없으면 포커스 가능한 옵션을 선택하고 오버레이를 닫은 뒤, 페이지의 다음 엘리먼트로 포커스를 옮겨요.
shift + tab 팝업 안의 이전 포커스 가능한 엘리먼트로 포커스를 옮겨요. 더 없으면 포커스 가능한 옵션을 선택하고 오버레이를 닫은 뒤, 페이지의 다음 엘리먼트로 포커스를 옮겨요.
enter 포커스된 옵션을 선택하고 팝업을 닫은 뒤 AutoComplete 엘리먼트로 포커스를 옮겨요.
space 포커스된 옵션을 선택하고 팝업을 닫은 뒤 AutoComplete 엘리먼트로 포커스를 옮겨요.
escape 팝업을 닫은 뒤 AutoComplete 엘리먼트로 포커스를 옮겨요.
아래 화살표 다음 옵션으로 포커스를 옮겨요. 더 없으면 시각 포커스는 그대로 유지돼요.
위 화살표 이전 옵션으로 포커스를 옮겨요. 더 없으면 시각 포커스는 그대로 유지돼요.
alt + 위 화살표 포커스된 옵션을 선택하고 팝업을 닫은 뒤 AutoComplete 엘리먼트로 포커스를 옮겨요.
왼쪽 화살표 현재 옵션에서 시각 포커스를 치우고 입력 커서를 한 글자 왼쪽으로 옮겨요.
오른쪽 화살표 현재 옵션에서 시각 포커스를 치우고 입력 커서를 한 글자 오른쪽으로 옮겨요.
home 커서가 이미 끝에 있지 않다면 입력 커서를 끝으로 옮기고, 그렇지 않으면 첫 번째 옵션으로 포커스를 옮겨요.
end 커서가 이미 처음에 있지 않다면 입력 커서를 처음으로 옮기고, 그렇지 않으면 마지막 옵션으로 포커스를 옮겨요.
pageUp 시각 포커스를 첫 번째 옵션으로 점프시켜요.
pageDown 시각 포커스를 마지막 옵션으로 점프시켜요.
shift + 아래 화살표 다음 옵션으로 포커스를 옮기고 선택 상태를 토글해요.
shift + 위 화살표 이전 옵션으로 포커스를 옮기고 선택 상태를 토글해요.
shift + space 가장 최근에 선택한 옵션과 포커스된 옵션 사이의 항목들을 선택해요.
control + shift + home 포커스된 옵션부터 첫 번째 옵션까지 모두 선택해요.
control + shift + end 포커스된 옵션부터 마지막 옵션까지 모두 선택해요.

칩 입력 키보드 지원

키 동작
backspace 입력 칸이 비어 있으면 바로 앞의 칩을 지워요.
왼쪽 화살표 입력 칸이 비어 있고 이전 칩이 있으면 그 칩으로 포커스를 옮겨요.

칩 키보드 지원

키 동작
왼쪽 화살표 이전 칩이 있으면 그 칩으로 포커스를 옮겨요.
오른쪽 화살표 다음 칩으로 포커스를 옮겨요. 더 없으면 입력 칸이 포커스를 받아요.
backspace 칩을 지우고 포커스를 입력 칸으로 옮겨요.
<label for="ac1">;Username</label>
<AutoComplete inputId="ac1" />

<span id="ac2">Email</span>
<AutoComplete aria-labelledby="ac2" />

<AutoComplete aria-label="City" />

기본 (Basic)

AutoComplete는 v-model prop으로 양방향 값을 묶어요. 여기에 더해, 결과를 조회하려면 suggestions prop과 complete 메서드도 필요해요. v-model은 사용자가 고른 최종 값을, suggestions는 화면에 보여 줄 후보 배열을, complete 이벤트 핸들러는 입력할 때마다 후보를 만들어 주는 역할이라고 기억해 두시면 돼요.

<AutoComplete v-model="value" :suggestions="items" @complete="search" />

지우기 아이콘 (Clear Icon)

showClear를 켜면 AutoComplete 값을 초기화할 수 있는 지우기 아이콘이 입력 칸에 추가돼요.

<AutoComplete v-model="value" showClear :suggestions="items" @complete="search" inputClass="w-56" />
Composition API Example
<template>
    <div class="card flex justify-center">
        <AutoComplete v-model="value" showClear :suggestions="items" @complete="search" inputClass="w-56" />
    </div>
</template>

<script setup>
import { ref } from "vue";

const value = ref(null);
const items = ref([]);

const search = (event) => {
    items.value = [...Array(10).keys()].map((item) => event.query + '-' + item);
}
<\/script>

비활성화 (Disabled)

disabled가 있으면 엘리먼트를 편집하거나 포커스할 수 없어요.

<AutoComplete disabled placeholder="Disabled" />
Composition API Example
<template>
    <div class="card flex justify-center">
        <AutoComplete disabled placeholder="Disabled" />
    </div>
</template>

<script setup>

<\/script>

드롭다운 (Dropdown)

dropdown prop을 켜면 입력 칸 옆에 버튼이 표시돼요. 이 버튼의 클릭 동작은 dropdownMode prop으로 정의하는데, 값으로 blank와 current를 받을 수 있어요. 기본 모드인 blank는 빈 문자열로 쿼리를 보내고, current는 입력 칸의 현재 값으로 쿼리를 보내요.

<AutoComplete v-model="value" dropdown :suggestions="items" @complete="search" />
Composition API Example
<template>
    <div class="card flex justify-center">
        <AutoComplete v-model="value" dropdown :suggestions="items" @complete="search" />
    </div>
</template>

<script setup>
import { ref } from "vue";

const value = ref(null);
const items = ref([]);

const search = (event) => {
    let _items = [...Array(10).keys()];

    items.value = event.query ? [...Array(10).keys()].map((item) => event.query + '-' + item) : _items;
}
<\/script>

채움 스타일 (Filled)

variant prop을 filled로 지정하면 기본 outlined 스타일보다 시각적으로 강조가 강한 모양으로 표시돼요.

<AutoComplete v-model="value" :suggestions="items" @complete="search" variant="filled" />
Composition API Example
<template>
    <div class="card flex justify-center">
        <AutoComplete v-model="value" :suggestions="items" @complete="search" variant="filled" />
    </div>
</template>

<script setup>
import { ref } from "vue";

const value = ref(null);
const items = ref([]);

const search = (event) => {
    items.value = [...Array(10).keys()].map((item) => event.query + '-' + item);
}
<\/script>

플로트 라벨 (Float Label)

포커스를 받으면 플로팅 라벨이 입력 칸 위로 떠 올라가요. 더 자세한 내용은 FloatLabel 문서를 참고하세요.

<FloatLabel>
    <AutoComplete v-model="value1" inputId="over_label" :suggestions="items" @complete="search" />
    <label for="over_label">Over Label</label>
</FloatLabel>

<FloatLabel variant="in">
    <AutoComplete v-model="value2" inputId="in_label" :suggestions="items" @complete="search" variant="filled" />
    <label for="in_label">In Label</label>
</FloatLabel>

<FloatLabel variant="on">
    <AutoComplete v-model="value3" inputId="on_label" :suggestions="items" @complete="search" />
    <label for="on_label">On Label</label>
</FloatLabel>
Composition API Example
<template>
    <div class="card flex flex-wrap justify-center items-end gap-4">
        <FloatLabel>
            <AutoComplete v-model="value1" inputId="over_label" :suggestions="items" @complete="search" />
            <label for="over_label">Over Label</label>
        </FloatLabel>

        <FloatLabel variant="in">
            <AutoComplete v-model="value2" inputId="in_label" :suggestions="items" @complete="search" variant="filled" />
            <label for="in_label">In Label</label>
        </FloatLabel>

        <FloatLabel variant="on">
            <AutoComplete v-model="value3" inputId="on_label" :suggestions="items" @complete="search" />
            <label for="on_label">On Label</label>
        </FloatLabel>
    </div>
</template>

<script setup>
import { ref } from "vue";

const value1 = ref('');
const value2 = ref('');
const value3 = ref('');
const items = ref([]);

const search = (event) => {
    items.value = [...Array(10).keys()].map((item) => event.query + '-' + item);
}
<\/script>

플루이드 (Fluid)

fluid prop을 true로 주면 컴포넌트가 컨테이너의 전체 너비를 차지해요.

<AutoComplete v-model="value" :suggestions="items" fluid @complete="search" />
Composition API Example
<template>
    <div class="card">
        <AutoComplete v-model="value" :suggestions="items" fluid @complete="search" />
    </div>
</template>

<script setup>
import { ref } from "vue";

const value = ref(null);
const items = ref([]);

const search = (event) => {
    items.value = [...Array(10).keys()].map((item) => event.query + '-' + item);
}
<\/script>

강제 선택 (Force Selection)

ForceSelection 모드는 직접 입력한 값을 검사해서 후보 목록에도 존재하는지 확인해요. 없다면 입력 값을 지워 버려서, 모델에 전달되는 값이 항상 후보 중 하나가 되도록 만들죠. 입력이 항상 후보 목록에서만 나오게 하려면 forceSelection만 켜면 돼요.

<AutoComplete v-model="selectedCountry" forceSelection optionLabel="name" :suggestions="filteredCountries" @complete="search" />
Composition API Example
<template>
    <div class="card flex justify-center">
        <AutoComplete v-model="selectedCountry" forceSelection optionLabel="name" :suggestions="filteredCountries" @complete="search" />
    </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { CountryService } from "@/service/CountryService";

onMounted(() => {
    CountryService.getCountries().then((data) => (countries.value = data));
});

const countries = ref();
const selectedCountry = ref();
const filteredCountries = ref();


const search = (event) => {
    setTimeout(() => {
        if (!event.query.trim().length) {
            filteredCountries.value = [...countries.value];
        } else {
            filteredCountries.value = countries.value.filter((country) => {
                return country.name.toLowerCase().startsWith(event.query.toLowerCase());
            });
        }
    }, 250);
}
<\/script>

폼 (Forms)

AutoComplete는 PrimeVue Forms 라이브러리와 매끄럽게 통합돼요.

<Form v-slot="$form" :resolver="resolver" :initialValues="initialValues" @submit="onFormSubmit" class="flex justify-center flex-col gap-4 w-full md:w-56">
    <div class="flex flex-col gap-1">
        <AutoComplete name="country.name" optionLabel="name" :suggestions="filteredCountries" @complete="search" fluid />
        <Message v-if="$form.country?.name?.invalid" severity="error" size="small" variant="simple">{{ $form.country.name.error?.message }}</Message>
    </div>
    <Button type="submit" severity="secondary" label="Submit" />
</Form>
Composition API Example
<template>
    <div class="card flex justify-center">
        <Form v-slot="$form" :resolver="resolver" :initialValues="initialValues" @submit="onFormSubmit" class="flex justify-center flex-col gap-4 w-full md:w-56">
            <div class="flex flex-col gap-1">
                <AutoComplete name="country.name" optionLabel="name" :suggestions="filteredCountries" @complete="search" fluid />
                <Message v-if="$form.country?.name?.invalid" severity="error" size="small" variant="simple">{{ $form.country.name.error?.message }}</Message>
            </div>
            <Button type="submit" severity="secondary" label="Submit" />
        </Form>
        <Toast />
    </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { zodResolver } from '@primevue/forms/resolvers/zod';
import { useToast } from "primevue/usetoast";
import { z } from 'zod';
import { CountryService } from "@/service/CountryService";

onMounted(() => {
    CountryService.getCountries().then((data) => (countries.value = data));
});

const initialValues = ref({
    country: { name: '' }
});
const resolver = ref(zodResolver(
    z.object({
        country: z.union([
            z.object({
                name: z.string().min(1, 'Country is required.')
            }),
            z.any().refine((val) => false, { message: 'Country is required.' })
        ])
    })
));
const countries = ref();
const selectedCountry = ref();
const filteredCountries = ref();
const toast = useToast();

const search = (event) => {
    setTimeout(() => {
        if (!event.query.trim().length) {
            filteredCountries.value = [...countries.value];
        } else {
            filteredCountries.value = countries.value.filter((country) => {
                return country.name.toLowerCase().startsWith(event.query.toLowerCase());
            });
        }
    }, 250);
};

const onFormSubmit = ({ valid }) => {
    if (valid) {
        toast.add({ severity: 'success', summary: 'Form is submitted.', life: 3000 });
    }
};
<\/script>

그룹 (Group)

옵션 그룹은 optionGroupLabel과 optionGroupChildren props로 지정해요.

<AutoComplete v-model="selectedCity" :suggestions="filteredCities" @complete="search" optionLabel="label" optionGroupLabel="label" optionGroupChildren="items" placeholder="Hint: type 'a'">
    <template #optiongroup="slotProps">
        <div class="flex items-center country-item">
            <img :alt="slotProps.option.label" src="https://primefaces.org/cdn/primevue/images/flag/flag_placeholder.png" :class="\`flag flag-\${slotProps.option.code.toLowerCase()} mr-2\`" style="width: 18px" />
            <div>{{ slotProps.option.label }}</div>
        </div>
    </template>
</AutoComplete>
Composition API Example
<template>
    <div class="card flex justify-center">
        <AutoComplete v-model="selectedCity" :suggestions="filteredCities" @complete="search" optionLabel="label" optionGroupLabel="label" optionGroupChildren="items" placeholder="Hint: type 'a'">
            <template #optiongroup="slotProps">
                <div class="flex items-center country-item">
                    <img :alt="slotProps.option.label" src="https://primefaces.org/cdn/primevue/images/flag/flag_placeholder.png" :class="\`flag flag-\${slotProps.option.code.toLowerCase()} mr-2\`" style="width: 18px" />
                    <div>{{ slotProps.option.label }}</div>
                </div>
            </template>
        </AutoComplete>
    </div>
</template>

<script setup>
import { ref } from "vue";
import { FilterMatchMode, FilterService } from '@primevue/core/api';

const selectedCity = ref();
const filteredCities = ref();
const groupedCities = ref([
    {
        label: 'Germany',
        code: 'DE',
        items: [
            { label: 'Berlin', value: 'Berlin' },
            { label: 'Frankfurt', value: 'Frankfurt' },
            { label: 'Hamburg', value: 'Hamburg' },
            { label: 'Munich', value: 'Munich' }
        ]
    },
    {
        label: 'USA',
        code: 'US',
        items: [
            { label: 'Chicago', value: 'Chicago' },
            { label: 'Los Angeles', value: 'Los Angeles' },
            { label: 'New York', value: 'New York' },
            { label: 'San Francisco', value: 'San Francisco' }
        ]
    },
    {
        label: 'Japan',
        code: 'JP',
        items: [
            { label: 'Kyoto', value: 'Kyoto' },
            { label: 'Osaka', value: 'Osaka' },
            { label: 'Tokyo', value: 'Tokyo' },
            { label: 'Yokohama', value: 'Yokohama' }
        ]
    }
]);

const search = (event) => {
    let query = event.query;
    let newFilteredCities = [];

    for (let country of groupedCities.value) {
        let filteredItems = FilterService.filter(country.items, ['label'], query, FilterMatchMode.CONTAINS);
        if (filteredItems && filteredItems.length) {
            newFilteredCities.push({...country, ...{items: filteredItems}});
        }
    }

    filteredCities.value = newFilteredCities;

}
<\/script>

Ifta 라벨 (Ifta Label)

IftaLabel은 입력 칸 안쪽에 위 정렬로 붙는 라벨을 만들 때 써요. 더 자세한 내용은 IftaLabel 문서를 참고하세요.

<IftaLabel>
    <AutoComplete v-model="value" inputId="ac" :suggestions="items" @complete="search" variant="filled" />
    <label for="ac">Identifier</label>
</IftaLabel>
Composition API Example
<template>
    <div class="card flex justify-center">
        <IftaLabel>
            <AutoComplete v-model="value" inputId="ac" :suggestions="items" @complete="search" variant="filled" />
            <label for="ac">Identifier</label>
        </IftaLabel>
    </div>
</template>

<script setup>
import { ref } from "vue";

const value = ref(null);
const items = ref([]);

const search = (event) => {
    items.value = [...Array(10).keys()].map((item) => event.query + '-' + item);
}
<\/script>

유효하지 않은 상태 (Invalid)

유효성 검사가 실패했음을 표시할 때는 invalid prop으로 invalid 상태를 보여 줘요. 폼 검증 라이브러리와 통합할 때 이 스타일을 활용하면 돼요.

<AutoComplete v-model="value1" :suggestions="items" @complete="search" :invalid="!value1" placeholder="Code" />
<AutoComplete v-model="value2" :suggestions="items" @complete="search" :invalid="!value2" variant="filled" placeholder="Code" />
Composition API Example
<template>
    <div class="card flex flex-wrap justify-center gap-4">
        <AutoComplete v-model="value1" :suggestions="items" @complete="search" :invalid="!value1" placeholder="Code" />
        <AutoComplete v-model="value2" :suggestions="items" @complete="search" :invalid="!value2" variant="filled" placeholder="Code" />
    </div>
</template>

<script setup>
import { ref } from "vue";

const value1 = ref('');
const value2 = ref('');
const items = ref([]);

const search = (event) => {
    items.value = [...Array(10).keys()].map((item) => event.query + '-' + item);
}
<\/script>

다중 선택 (Multiple)

multiple prop을 쓰면 여러 값을 고를 수 있는 모드가 켜져요. 이때는 value 참조가 배열이어야 한다는 점만 기억하시면 돼요.

<label for="multiple-ac-1" class="font-bold mb-2 block">With Typeahead</label>
<AutoComplete v-model="value1" inputId="multiple-ac-1" multiple fluid :suggestions="items" @complete="search" />

<label for="multiple-ac-2" class="font-bold mt-8 mb-2 block">Without Typeahead</label>
<AutoComplete v-model="value2" inputId="multiple-ac-2" multiple fluid @complete="search" :typeahead="false" />
Composition API Example
<template>
    <div class="card">
        <label for="multiple-ac-1" class="font-bold mb-2 block">With Typeahead</label>
        <AutoComplete v-model="value1" inputId="multiple-ac-1" multiple fluid :suggestions="items" @complete="search" />

        <label for="multiple-ac-2" class="font-bold mt-8 mb-2 block">Without Typeahead</label>
        <AutoComplete v-model="value2" inputId="multiple-ac-2" multiple fluid @complete="search" :typeahead="false" />
    </div>
</template>

<script setup>
import { ref } from "vue";

const value1 = ref(null);
const value2 = ref(null);
const items = ref([]);

const search = (event) => {
    items.value = [...Array(10).keys()].map((item) => event.query + '-' + item);
}
<\/script>

객체 (Objects)

optionLabel prop을 쓰면 객체를 다룰 수 있어요. 이 prop은 후보로 보여 줄 라벨을 정의하는 건데, 모델에 전달되는 값은 여전히 후보의 객체 인스턴스 그대로예요. 예를 들어 name과 code 필드를 가진 Country 객체가 {name: "United States", code:"USA"}처럼 생겼다고 볼 수 있죠.

<AutoComplete v-model="selectedCountry" optionLabel="name" :suggestions="filteredCountries" @complete="search" />
Composition API Example
<template>
    <div class="card flex justify-center">
        <AutoComplete v-model="selectedCountry" optionLabel="name" :suggestions="filteredCountries" @complete="search" />
    </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { CountryService } from "@/service/CountryService";

onMounted(() => {
    CountryService.getCountries().then((data) => (countries.value = data));
});

const countries = ref();
const selectedCountry = ref();
const filteredCountries = ref();


const search = (event) => {
    setTimeout(() => {
        if (!event.query.trim().length) {
            filteredCountries.value = [...countries.value];
        } else {
            filteredCountries.value = countries.value.filter((country) => {
                return country.name.toLowerCase().startsWith(event.query.toLowerCase());
            });
        }
    }, 250);
}
<\/script>

크기 (Sizes)

AutoComplete는 기본 크기 외에 small과 large 크기를 제공해요.

<AutoComplete v-model="value1" :suggestions="items" @complete="search" size="small" placeholder="Small" dropdown />
<AutoComplete v-model="value2" :suggestions="items" @complete="search" placeholder="Normal" dropdown />
<AutoComplete v-model="value3" :suggestions="items" @complete="search" size="large" placeholder="Large" dropdown />
Composition API Example
<template>
    <div class="card flex flex-col items-center gap-4">
        <AutoComplete v-model="value1" :suggestions="items" @complete="search" size="small" placeholder="Small" dropdown />
        <AutoComplete v-model="value2" :suggestions="items" @complete="search" placeholder="Normal" dropdown />
        <AutoComplete v-model="value3" :suggestions="items" @complete="search" size="large" placeholder="Large" dropdown />
    </div>
</template>

<script setup>
import { ref } from "vue";

const value1 = ref(null);
const value2 = ref(null);
const value3 = ref(null);
const items = ref([]);

const search = () => {
    items.value = [];
}
<\/script>

템플릿 (Template)

AutoComplete는 템플릿을 통해 커스터마이징할 수 있는 여러 슬롯을 제공해요.

<AutoComplete v-model="selectedCountry" optionLabel="name" :suggestions="filteredCountries" @complete="search">
    <template #option="slotProps">
        <div class="flex items-center">
            <img :alt="slotProps.option.name" src="https://primefaces.org/cdn/primevue/images/flag/flag_placeholder.png" :class="\`flag flag-\${slotProps.option.code.toLowerCase()} mr-2\`" style="width: 18px" />
            <div>{{ slotProps.option.name }}</div>
        </div>
    </template>
    <template #header>
        <div class="font-medium px-3 py-2">Available Countries</div>
    </template>
    <template #footer>
        <div class="px-3 py-3">
            <Button label="Add New" fluid severity="secondary" text size="small" icon="pi pi-plus" />
        </div>
    </template>
</AutoComplete>
Composition API Example
<template>
    <div class="card flex justify-center">
        <AutoComplete v-model="selectedCountry" optionLabel="name" :suggestions="filteredCountries" @complete="search">
            <template #option="slotProps">
                <div class="flex items-center">
                    <img :alt="slotProps.option.name" src="https://primefaces.org/cdn/primevue/images/flag/flag_placeholder.png" :class="\`flag flag-\${slotProps.option.code.toLowerCase()} mr-2\`" style="width: 18px" />
                    <div>{{ slotProps.option.name }}</div>
                </div>
            </template>
            <template #header>
                <div class="font-medium px-3 py-2">Available Countries</div>
            </template>
            <template #footer>
                <div class="px-3 py-3">
                    <Button label="Add New" fluid severity="secondary" text size="small" icon="pi pi-plus" />
                </div>
            </template>
        </AutoComplete>
    </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { CountryService } from "@/service/CountryService";

onMounted(() => {
    CountryService.getCountries().then((data) => (countries.value = data));
});

const countries = ref();
const selectedCountry = ref();
const filteredCountries = ref();


const search = (event) => {
    setTimeout(() => {
        if (!event.query.trim().length) {
            filteredCountries.value = [...countries.value];
        } else {
            filteredCountries.value = countries.value.filter((country) => {
                return country.name.toLowerCase().startsWith(event.query.toLowerCase());
            });
        }
    }, 250);
}
<\/script>

가상 스크롤 (Virtual Scroll)

가상 스크롤링(Virtual Scrolling)은 큰 목록을 성능 좋게 렌더링하는 방법이에요. 스크롤 동작의 설정은 virtualScrollerOptions로 정의하는데, 항목 하나의 높이를 정하는 itemSize가 필수 값이에요. 설정 API에 대한 자세한 내용은 VirtualScroller 문서를 참고하세요.

<AutoComplete v-model="selectedItem" :suggestions="filteredItems" @complete="searchItems" :virtualScrollerOptions="{ itemSize: 38 }" optionLabel="label" dropdown />
Composition API Example
<template>
    <div class="card flex justify-center">
        <AutoComplete v-model="selectedItem" :suggestions="filteredItems" @complete="searchItems" :virtualScrollerOptions="{ itemSize: 38 }" optionLabel="label" dropdown />
    </div>
</template>

<script setup>
import { ref } from "vue";

const items = ref(Array.from({ length: 1000 }, (_, i) => ({ label: \`Item #\${i}\`, value: i })));
const selectedItem = ref();
const filteredItems = ref();
const searchItems = (event) => {
    //in a real application, make a request to a remote url with the query and return filtered results, for demo we filter at client side
    let query = event.query;
    let _filteredItems = [];

    for (let i = 0; i < items.value.length; i++) {
        let item = items.value[i];

        if (item.label.toLowerCase().indexOf(query.toLowerCase()) === 0) {
            _filteredItems.push(item);
        }
    }

    filteredItems.value = _filteredItems;
};
<\/script>

자동 완성 (Auto Complete)

Props

이름 타입 기본값 설명
modelValue any - 컴포넌트의 값이에요.
defaultValue any - modelValue로 제어하지 않을 때 입력의 기본값이에요.
name string - 엘리먼트의 name 속성이에요. 주로 폼 제출에 써요.
suggestions any[] - 표시할 후보 배열이에요.
optionLabel string | Function - 옵션의 라벨로 쓸 속성 이름이나 getter 함수예요.
optionDisabled string | Function - 옵션의 disabled 플래그로 쓸 속성 이름이나 getter 함수예요. 정의하지 않으면 false가 기본값이에요.
optionGroupLabel string | Function - 옵션 그룹의 라벨로 쓸 속성 이름이나 getter 함수예요.
optionGroupChildren string | Function - 옵션 그룹의 자식 옵션을 가리키는 속성 이름이나 getter 함수예요.
typeahead boolean true typeahead가 활성 상태인지 여부예요.
scrollHeight string 14rem 후보 오버레이의 최대 높이예요.
dropdown boolean false 켜면 입력 칸 옆에 버튼을 표시해요.
dropdownMode HintedString<"blank" | "current"> blank 드롭다운 버튼의 동작을 지정해요. 기본인 'blank' 모드는 빈 문자열을, 'current' 모드는 입력 값을 보내요.
multiple boolean false 여러 값을 선택할 수 있는지 지정해요.
showClear boolean false 켜면 값을 지울 수 있는 지우기 아이콘을 표시해요.
placeholder string - 아무 옵션도 선택하지 않았을 때 표시할 기본 텍스트예요.
loading boolean false autocomplete가 로딩 상태인지 여부예요.
size HintedString<"small" | "large"> - 컴포넌트의 크기를 정의해요.
invalid boolean false 있으면 컴포넌트에 invalid 상태 스타일이 적용돼야 함을 지정해요.
disabled boolean false 있으면 컴포넌트가 비활성화돼야 함을 지정해요.
variant null | HintedString<"outlined" | "filled"> null 컴포넌트의 입력 variant를 지정해요.
dataKey string - 옵션을 고유하게 식별하는 속성이에요.
minLength number 1 검색을 시작하기 위한 최소 문자 수예요.
delay number 300 쿼리를 보내기 전까지 입력 사이를 기다리는 지연 시간이에요.
appendTo HTMLElement | HintedString<"body" | "self"> body 오버레이를 어디에 붙일지 지정하는 유효한 쿼리 셀렉터나 HTMLElement예요. 특별 키워드로는 문서 body를 뜻하는 'body'와 엘리먼트 자신을 뜻하는 'self'가 있어요.
forceSelection boolean false 있으면 입력이 후보와 맞지 않을 때 자동 완성이 직접 입력 값을 지워서, 후보에서 나온 값만 받도록 강제해요.
completeOnFocus boolean false 입력이 포커스를 받을 때 쿼리를 실행할지 여부예요.
inputId string - 내부 입력 엘리먼트의 식별자예요.
inputStyle object - 입력 칸의 인라인 스타일이에요.
inputClass string | object - 입력 칸의 스타일 클래스예요.
panelStyle object - 오버레이의 인라인 스타일이에요.
panelClass string | object - 오버레이의 스타일 클래스예요.
overlayStyle object - 오버레이의 인라인 스타일이에요.
overlayClass string | object - 오버레이의 스타일 클래스예요.
dropdownIcon string - 드롭다운에 표시할 아이콘이에요.
dropdownClass string | object - 드롭다운 버튼의 스타일 클래스예요.
loadingIcon string - 로딩 상태에 표시할 아이콘이에요.
loader string - 로딩 상태에 표시할 아이콘이에요.
removeTokenIcon string - 칩 제거 동작에 표시할 아이콘이에요.
chipIcon string - 칩 제거 동작에 표시할 아이콘이에요.
virtualScrollerOptions any - virtualScroller 기능을 쓸지 여부예요. VirtualScroller 컴포넌트의 속성들을 객체 형태로 넣을 수 있어요.
autoOptionFocus boolean false 오버레이가 나타났을 때 첫 번째 보이는 엘리먼트나 선택된 엘리먼트에 포커스를 둘지 여부예요.
selectOnFocus boolean false 켜면 포커스된 옵션이 선택돼요.
focusOnHover boolean true 켜면 마우스를 올린 옵션에 포커스가 놓여요.
searchLocale string - 검색에 쓸 로케일이에요. 기본 로케일은 호스트 환경의 현재 로케일이에요.
searchMessage string '{0} results are available' 필터링 결과가 있을 때 숨겨진 접근성 필드에 표시할 텍스트예요. 기본값은 PrimeVue 로케일 설정 값을 따라요.
selectionMessage string '{0} items selected' 옵션을 선택했을 때 숨겨진 접근성 필드에 표시할 텍스트예요. 기본값은 PrimeVue 로케일 설정 값을 따라요.
emptySelectionMessage string No selected item 아무 옵션도 선택하지 않았을 때 숨겨진 접근성 필드에 표시할 텍스트예요. 기본값은 PrimeVue 로케일 설정 값을 따라요.
emptySearchMessage string No results found 필터링 결과가 없을 때 표시할 텍스트예요. 기본값은 PrimeVue 로케일 설정 값을 따라요.
showEmptyMessage boolean true 켜면 빈 검색 메시지가 보여요.
tabindex string | number - 탭 이동 순서에서의 인덱스예요.
fluid boolean null 켜면 컨테이너 너비의 100%를 차지해요.
ariaLabel string - 대화형 엘리먼트에 라벨을 붙이는 문자열 값을 정의해요.
ariaLabelledby string - 내부 입력 엘리먼트의 식별자예요.
formControl Record<string, any> - 폼 컨트롤 객체예요. 주로 검증과 폼 상태를 다룰 때 써요.
dt any - 컴포넌트에 디자인 토큰으로 스코프된 CSS 변수를 만들어 줘요.
pt PassThrough - 컴포넌트 내부 DOM 엘리먼트에 속성을 전달할 때 써요.
ptOptions any - 컴포넌트의 passthrough(pt) 옵션을 설정할 때 써요.
unstyled boolean false 켜면 코어에서 컴포넌트 관련 스타일을 제거해요.

Pass Through Options (패스 스루 옵션)

이름 타입 설명
root AutoCompletePassThroughOptionType root의 DOM 엘리먼트에 속성을 전달할 때 써요.
pcInputText any InputText 컴포넌트에 속성을 전달할 때 써요.
inputMultiple AutoCompletePassThroughOptionType input multiple의 DOM 엘리먼트에 속성을 전달할 때 써요.
chipItem AutoCompletePassThroughOptionType chip의 DOM 엘리먼트에 속성을 전달할 때 써요.
pcChip any Chip에 속성을 전달할 때 써요.
chipIcon AutoCompletePassThroughOptionType chip icon의 DOM 엘리먼트에 속성을 전달할 때 써요.
input AutoCompletePassThroughOptionType input chip의 DOM 엘리먼트에 속성을 전달할 때 써요.
inputChip AutoCompletePassThroughOptionType input chip의 DOM 엘리먼트에 속성을 전달할 때 써요.
loader AutoCompletePassThroughOptionType loader의 DOM 엘리먼트에 속성을 전달할 때 써요.
clearIcon AutoCompletePassThroughOptionType clear icon의 DOM 엘리먼트에 속성을 전달할 때 써요.
dropdown AutoCompletePassThroughOptionType dropdown의 DOM 엘리먼트에 속성을 전달할 때 써요.
dropdownIcon AutoCompletePassThroughOptionType dropdown icon의 DOM 엘리먼트에 속성을 전달할 때 써요.
overlay AutoCompletePassThroughOptionType overlay의 DOM 엘리먼트에 속성을 전달할 때 써요.
virtualScroller any VirtualScroller 컴포넌트에 속성을 전달할 때 써요.
listContainer AutoCompletePassThroughOptionType list container의 DOM 엘리먼트에 속성을 전달할 때 써요.
list AutoCompletePassThroughOptionType list의 DOM 엘리먼트에 속성을 전달할 때 써요.
optionGroup AutoCompletePassThroughOptionType option group의 DOM 엘리먼트에 속성을 전달할 때 써요.
option AutoCompletePassThroughOptionType option의 DOM 엘리먼트에 속성을 전달할 때 써요.
emptyMessage AutoCompletePassThroughOptionType empty message의 DOM 엘리먼트에 속성을 전달할 때 써요.
searchResultMessage AutoCompletePassThroughOptionType search result message의 DOM 엘리먼트에 속성을 전달할 때 써요.
selectedMessage AutoCompletePassThroughOptionType selected message의 DOM 엘리먼트에 속성을 전달할 때 써요.
hooks any 모든 라이프사이클 훅을 관리할 때 써요.
transition AutoCompletePassThroughTransitionType Vue Transition API를 제어할 때 써요.

테마 (Theming)

CSS 클래스 (CSS Classes)

클래스 설명
p-autocomplete root 엘리먼트의 클래스 이름이에요.
p-autocomplete-input input 엘리먼트의 클래스 이름이에요.
p-autocomplete-input-multiple input multiple 엘리먼트의 클래스 이름이에요.
p-autocomplete-clear-icon clear icon 엘리먼트의 클래스 이름이에요.
p-autocomplete-chip-item chip item 엘리먼트의 클래스 이름이에요.
p-autocomplete-chip chip 엘리먼트의 클래스 이름이에요.
p-autocomplete-chip-icon chip icon 엘리먼트의 클래스 이름이에요.
p-autocomplete-input-chip input chip 엘리먼트의 클래스 이름이에요.
p-autocomplete-loader loader 엘리먼트의 클래스 이름이에요.
p-autocomplete-dropdown dropdown 엘리먼트의 클래스 이름이에요.
p-autocomplete-overlay panel 엘리먼트의 클래스 이름이에요.
p-autocomplete-list list 엘리먼트의 클래스 이름이에요.
p-autocomplete-list-container list container 엘리먼트의 클래스 이름이에요.
p-autocomplete-option-group option group 엘리먼트의 클래스 이름이에요.
p-autocomplete-option option 엘리먼트의 클래스 이름이에요.
p-autocomplete-empty-message empty message 엘리먼트의 클래스 이름이에요.

디자인 토큰 (Design Tokens)

토큰 CSS 변수 설명
autocomplete.background --p-autocomplete-background root의 배경이에요.
autocomplete.disabled.background --p-autocomplete-disabled-background root의 비활성 배경이에요.
autocomplete.filled.background --p-autocomplete-filled-background root의 filled 배경이에요.
autocomplete.filled.hover.background --p-autocomplete-filled-hover-background root의 filled hover 배경이에요.
autocomplete.filled.focus.background --p-autocomplete-filled-focus-background root의 filled focus 배경이에요.
autocomplete.border.color --p-autocomplete-border-color root의 테두리 색이에요.
autocomplete.hover.border.color --p-autocomplete-hover-border-color root의 hover 테두리 색이에요.
autocomplete.focus.border.color --p-autocomplete-focus-border-color root의 focus 테두리 색이에요.
autocomplete.invalid.border.color --p-autocomplete-invalid-border-color root의 invalid 테두리 색이에요.
autocomplete.color --p-autocomplete-color root의 색이에요.
autocomplete.disabled.color --p-autocomplete-disabled-color root의 비활성 색이에요.
autocomplete.placeholder.color --p-autocomplete-placeholder-color root의 placeholder 색이에요.
autocomplete.invalid.placeholder.color --p-autocomplete-invalid-placeholder-color root의 invalid placeholder 색이에요.
autocomplete.shadow --p-autocomplete-shadow root의 그림자예요.
autocomplete.padding.x --p-autocomplete-padding-x root의 가로 패딩이에요.
autocomplete.padding.y --p-autocomplete-padding-y root의 세로 패딩이에요.
autocomplete.border.radius --p-autocomplete-border-radius root의 테두리 반경이에요.
autocomplete.focus.ring.width --p-autocomplete-focus-ring-width root의 focus ring 너비예요.
autocomplete.focus.ring.style --p-autocomplete-focus-ring-style root의 focus ring 스타일이에요.
autocomplete.focus.ring.color --p-autocomplete-focus-ring-color root의 focus ring 색이에요.
autocomplete.focus.ring.offset --p-autocomplete-focus-ring-offset root의 focus ring 오프셋이에요.
autocomplete.focus.ring.shadow --p-autocomplete-focus-ring-shadow root의 focus ring 그림자예요.
autocomplete.transition.duration --p-autocomplete-transition-duration root의 전환 지속 시간이에요.
autocomplete.overlay.background --p-autocomplete-overlay-background overlay의 배경이에요.
autocomplete.overlay.border.color --p-autocomplete-overlay-border-color overlay의 테두리 색이에요.
autocomplete.overlay.border.radius --p-autocomplete-overlay-border-radius overlay의 테두리 반경이에요.
autocomplete.overlay.color --p-autocomplete-overlay-color overlay의 색이에요.
autocomplete.overlay.shadow --p-autocomplete-overlay-shadow overlay의 그림자예요.
autocomplete.list.padding --p-autocomplete-list-padding list의 패딩이에요.
autocomplete.list.gap --p-autocomplete-list-gap list의 간격이에요.
autocomplete.option.focus.background --p-autocomplete-option-focus-background option의 focus 배경이에요.
autocomplete.option.selected.background --p-autocomplete-option-selected-background option의 선택 배경이에요.
autocomplete.option.selected.focus.background --p-autocomplete-option-selected-focus-background option의 선택 focus 배경이에요.
autocomplete.option.color --p-autocomplete-option-color option의 색이에요.
autocomplete.option.focus.color --p-autocomplete-option-focus-color option의 focus 색이에요.
autocomplete.option.selected.color --p-autocomplete-option-selected-color option의 선택 색이에요.
autocomplete.option.selected.focus.color --p-autocomplete-option-selected-focus-color option의 선택 focus 색이에요.
autocomplete.option.padding --p-autocomplete-option-padding option의 패딩이에요.
autocomplete.option.border.radius --p-autocomplete-option-border-radius option의 테두리 반경이에요.
autocomplete.option.group.background --p-autocomplete-option-group-background option group의 배경이에요.
autocomplete.option.group.color --p-autocomplete-option-group-color option group의 색이에요.
autocomplete.option.group.font.weight --p-autocomplete-option-group-font-weight option group의 글자 두께예요.
autocomplete.option.group.padding --p-autocomplete-option-group-padding option group의 패딩이에요.
autocomplete.dropdown.width --p-autocomplete-dropdown-width dropdown의 너비예요.
autocomplete.dropdown.sm.width --p-autocomplete-dropdown-sm-width dropdown의 sm 너비예요.
autocomplete.dropdown.lg.width --p-autocomplete-dropdown-lg-width dropdown의 lg 너비예요.
autocomplete.dropdown.border.color --p-autocomplete-dropdown-border-color dropdown의 테두리 색이에요.
autocomplete.dropdown.hover.border.color --p-autocomplete-dropdown-hover-border-color dropdown의 hover 테두리 색이에요.
autocomplete.dropdown.active.border.color --p-autocomplete-dropdown-active-border-color dropdown의 active 테두리 색이에요.
autocomplete.dropdown.border.radius --p-autocomplete-dropdown-border-radius dropdown의 테두리 반경이에요.
autocomplete.dropdown.focus.ring.width --p-autocomplete-dropdown-focus-ring-width dropdown의 focus ring 너비예요.
autocomplete.dropdown.focus.ring.style --p-autocomplete-dropdown-focus-ring-style dropdown의 focus ring 스타일이에요.
autocomplete.dropdown.focus.ring.color --p-autocomplete-dropdown-focus-ring-color dropdown의 focus ring 색이에요.
autocomplete.dropdown.focus.ring.offset --p-autocomplete-dropdown-focus-ring-offset dropdown의 focus ring 오프셋이에요.
autocomplete.dropdown.focus.ring.shadow --p-autocomplete-dropdown-focus-ring-shadow dropdown의 focus ring 그림자예요.
autocomplete.dropdown.background --p-autocomplete-dropdown-background dropdown의 배경이에요.
autocomplete.dropdown.hover.background --p-autocomplete-dropdown-hover-background dropdown의 hover 배경이에요.
autocomplete.dropdown.active.background --p-autocomplete-dropdown-active-background dropdown의 active 배경이에요.
autocomplete.dropdown.color --p-autocomplete-dropdown-color dropdown의 색이에요.
autocomplete.dropdown.hover.color --p-autocomplete-dropdown-hover-color dropdown의 hover 색이에요.
autocomplete.dropdown.active.color --p-autocomplete-dropdown-active-color dropdown의 active 색이에요.
autocomplete.chip.border.radius --p-autocomplete-chip-border-radius chip의 테두리 반경이에요.
autocomplete.chip.focus.background --p-autocomplete-chip-focus-background chip의 focus 배경이에요.
autocomplete.chip.focus.color --p-autocomplete-chip-focus-color chip의 focus 색이에요.
autocomplete.empty.message.padding --p-autocomplete-empty-message-padding empty message의 패딩이에요.

더 알아보기 (Learn more)

label 태그나 aria 속성으로 스크린 리더 접근성을 챙기고, v-model·suggestions·complete 세 가지가 기본 조합이라는 점만 잡아 두면 나머지는 필요할 때 하나씩 붙여 가면 돼요. 플로트 라벨은 FloatLabel 문서에서, Ifta 라벨은 IftaLabel 문서에서, 가상 스크롤 설정은 VirtualScroller 문서에서 각각 더 깊게 살펴볼 수 있어요.