VerificationCode
Поле для кода подтверждения из четырёх или шести цифр в крупном и компактном виде: ячейки и разделитель добавляют части, а подпись и подсказку даёт Field.
Импорт
ts
import { VerificationCode, VerificationCodeSlot, VerificationCodeSeparator } from '@prosper/ui'Анатомия
vue
<VerificationCode>
<VerificationCodeSlot />
<VerificationCodeSeparator />
</VerificationCode>Примеры
По умолчанию
v-model с настоящим ref, а событие complete приходит, когда набраны все цифры.
vue
<script setup lang="ts">
import { ref } from 'vue'
import {
Field,
FieldHint,
FieldLabel,
VerificationCode,
VerificationCodeSlot,
} from '@prosper/ui'
const code = ref('')
const entered = ref('')
</script>
<template>
<div
style="
display: flex;
flex-direction: column;
gap: var(--prosper-spacing-3xl);
"
>
<Field>
<FieldLabel>Код из SMS</FieldLabel>
<VerificationCode v-model="code" :digits="4" @complete="entered = $event">
<VerificationCodeSlot
v-for="index in 4"
:key="index"
:index="index - 1"
/>
</VerificationCode>
<FieldHint>Мы отправили четыре цифры на ваш номер.</FieldHint>
</Field>
<p v-if="entered" style="margin: 0">Введён полный код: {{ entered }}</p>
</div>
</template>Типы
Компактный код со всеми размерами, а шесть цифр с дефисом помещаются в окно 320.
vue
<script setup lang="ts">
import {
Field,
FieldLabel,
VerificationCode,
VerificationCodeSeparator,
VerificationCodeSlot,
} from '@prosper/ui'
const sizes = ['sm', 'md', 'lg', 'xl'] as const
</script>
<template>
<div
style="
display: flex;
flex-direction: column;
gap: var(--prosper-spacing-4xl);
min-inline-size: 0;
"
>
<Field v-for="size in sizes" :key="size" :size="size">
<FieldLabel>{{ size }}</FieldLabel>
<VerificationCode variant="compact" :digits="4" value="123">
<VerificationCodeSlot
v-for="index in 4"
:key="index"
:index="index - 1"
/>
</VerificationCode>
</Field>
<Field size="xl">
<FieldLabel>Шесть цифр</FieldLabel>
<VerificationCode variant="compact" value="123">
<VerificationCodeSlot
v-for="index in 3"
:key="index"
:index="index - 1"
/>
<VerificationCodeSeparator />
<VerificationCodeSlot
v-for="index in 3"
:key="index"
:index="index + 2"
/>
</VerificationCode>
</Field>
</div>
</template>Размеры
Три размера ячейки: sm, md и lg, а начальный код задаёт атрибут value.
vue
<script setup lang="ts">
import {
Field,
FieldLabel,
VerificationCode,
VerificationCodeSlot,
} from '@prosper/ui'
const sizes = ['sm', 'md', 'lg'] as const
</script>
<template>
<div
style="
display: flex;
flex-direction: column;
gap: var(--prosper-spacing-4xl);
"
>
<Field v-for="size in sizes" :key="size" :size="size">
<FieldLabel>{{ size }}</FieldLabel>
<VerificationCode :digits="4" value="123">
<VerificationCodeSlot
v-for="index in 4"
:key="index"
:index="index - 1"
/>
</VerificationCode>
</Field>
</div>
</template>Четыре и шесть цифр
digits выбирает, сколько цифр принимает поле: 4 или 6 (по умолчанию), а ячейки и дефис между группами рисуют VerificationCodeSlot и VerificationCodeSeparator.
vue
<script setup lang="ts">
import {
Field,
FieldLabel,
VerificationCode,
VerificationCodeSeparator,
VerificationCodeSlot,
} from '@prosper/ui'
</script>
<template>
<div
style="
display: flex;
flex-direction: column;
gap: var(--prosper-spacing-4xl);
min-inline-size: 0;
"
>
<Field size="sm">
<FieldLabel>Четыре ячейки</FieldLabel>
<VerificationCode :digits="4" value="12">
<VerificationCodeSlot
v-for="index in 4"
:key="index"
:index="index - 1"
/>
</VerificationCode>
</Field>
<Field size="sm">
<FieldLabel>Шесть ячеек</FieldLabel>
<VerificationCode value="123">
<VerificationCodeSlot
v-for="index in 3"
:key="index"
:index="index - 1"
/>
<VerificationCodeSeparator />
<VerificationCodeSlot
v-for="index in 3"
:key="index"
:index="index + 2"
/>
</VerificationCode>
</Field>
</div>
</template>Состояния
invalid у Field включает красные ячейки, текст ошибки кладите в FieldError, а disabled отключает поле.
vue
<script setup lang="ts">
import {
Field,
FieldError,
FieldLabel,
VerificationCode,
VerificationCodeSlot,
} from '@prosper/ui'
</script>
<template>
<div
style="
display: flex;
flex-direction: column;
gap: var(--prosper-spacing-4xl);
"
>
<Field>
<FieldLabel>Пустое</FieldLabel>
<VerificationCode :digits="4">
<VerificationCodeSlot
v-for="index in 4"
:key="index"
:index="index - 1"
/>
</VerificationCode>
</Field>
<Field>
<FieldLabel>Весь код</FieldLabel>
<VerificationCode :digits="4" value="1234">
<VerificationCodeSlot
v-for="index in 4"
:key="index"
:index="index - 1"
/>
</VerificationCode>
</Field>
<Field invalid>
<FieldLabel>С ошибкой</FieldLabel>
<VerificationCode :digits="4" value="1234">
<VerificationCodeSlot
v-for="index in 4"
:key="index"
:index="index - 1"
/>
</VerificationCode>
<FieldError>Код не подошёл, попробуйте ещё раз.</FieldError>
</Field>
<Field disabled>
<FieldLabel>Отключённое</FieldLabel>
<VerificationCode :digits="4" value="123">
<VerificationCodeSlot
v-for="index in 4"
:key="index"
:index="index - 1"
/>
</VerificationCode>
</Field>
</div>
</template>Обязательное поле
placeholder задаёт символ пустых ячеек (по умолчанию 0), required у Field включает проверку формы, а name уходит на input.
vue
<script setup lang="ts">
import {
Field,
FieldLabel,
VerificationCode,
VerificationCodeSlot,
} from '@prosper/ui'
</script>
<template>
<Field required>
<FieldLabel>Код из SMS</FieldLabel>
<VerificationCode name="code" placeholder="•" :digits="4">
<VerificationCodeSlot
v-for="index in 4"
:key="index"
:index="index - 1"
/>
</VerificationCode>
</Field>
</template>API
VerificationCode
Props
| Имя | Тип | По умолчанию | Описание |
|---|---|---|---|
modelValue | string | — | Код: строка цифр, состояние хранит приложение и обновляет его по событию update:modelValue, а без значения поле нативное и начальный код задаёт атрибут value. |
digits | 4 | 6 | 6 | Сколько цифр принимает поле: 4 или 6, а ячейки и дефис между группами рисуют VerificationCodeSlot и VerificationCodeSeparator (их индексы должны идти от нуля до digits - 1). |
variant | 'default' | 'compact' | — | Вид: default рисует крупные ячейки, compact рисует ячейки высотой с поле ввода и сжимает ряд в узкой колонке, а без значения default, в виде cabinet compact. |
size | 'sm' | 'md' | 'lg' | 'xl' | — | Размер ячейки: у default sm 64 px, md 80 px, lg и xl 96 px, у compact как у поля ввода; без значения берёт Field, вне Field md, в виде cabinet xl. |
required | boolean | — | Обязательное поле: нативный required, а без значения required берёт Field (он же рисует звёздочку у подписи). |
invalid | boolean | — | Ошибка: красные рамки ячеек и aria-invalid, а без значения её берёт Field; у отключённого поля не действует. |
disabled | boolean | — | Отключает поле: ячейки выглядят отключёнными и получают курсор not-allowed, а без значения disabled берёт Field. |
autocomplete | string | — | Подсказка автозаполнения для браузера: по умолчанию one-time-code. |
События
| Имя | Тип | Описание |
|---|---|---|
update:modelValue | (value: string) => void | Пользователь изменил код, передаётся новое значение (только цифры, не длиннее digits), например для v-model; если modelValue задан и приложение его не обновило, поле вернётся к прежнему значению. |
complete | (value: string) => void | Набраны все цифры: приходит сразу после update:modelValue с полным кодом, в том числе при вставке и автозаполнении из SMS. |
Слоты
| Имя | Тип | Описание |
|---|---|---|
default | {} | Части поля: VerificationCodeSlot для каждой ячейки и VerificationCodeSeparator между группами. |
VerificationCodeSlot
Одна ячейка кода: показывает цифру своего номера или символ пустой ячейки и берёт состояние у VerificationCode.
Props
| Имя | Тип | По умолчанию | Описание |
|---|---|---|---|
index | number | обязательный | Номер ячейки с нуля: берётся цифра кода с этим номером, а активной ячейкой становится та, что получит следующую цифру. |
VerificationCodeSeparator
Разделитель групп ячеек: по умолчанию дефис, а размер берёт от корня.
Слоты
| Имя | Тип | Описание |
|---|---|---|
default | {} | Знак разделителя вместо дефиса. |
Доступность
| Клавиша | Действие |
|---|---|
| Backspace | удалить последнюю цифру в редактируемом поле |
| Стрелки, Home, End | курсор остаётся в конце кода |
- Это одно нативное поле, а не шесть:
inputсautocomplete="one-time-code",inputmode="numeric"иpatternизdigitsцифр по умолчанию, поэтому автозаполнение из SMS и цифровая клавиатура работают нативно, а нарисованные ячейки и разделитель скрыты от скринридера. - Имя, описание, звёздочку и ошибку даёт Field, а полю без него нужно имя через
aria-label,aria-labelledbyилиtitle, иначе в режиме разработки выводится предупреждение. patternпо умолчанию не пропускает в форму неполный код,required— пустой, аinvalidставитaria-invalid="true"и у отключённого поля не показывается.- В поле остаются только цифры (полноширинные приводятся к обычным), длина обрезается до
digits, вставка заменяет код целиком, а в полеreadonlyигнорируется. - Щелчок по ячейке ставит курсор в конец кода.
- Корень это
divсclassиstyle,name,form,id,readonly,autofocusиaria-*уходят на поле, аplaceholderзадаёт только символ пустых ячеек и наinputне попадает.