---
title: "AuthForm"
description: "Готовая форма входа, регистрации или сброса пароля: поля, кнопки сервисов и отправка."
canonical_url: "https://b24-ui.bx-shef.by/docs/components/auth-form"
---
# AuthForm

> Готовая форма входа, регистрации или сброса пароля: поля, кнопки сервисов и отправка.

## Использование

Компонент AuthForm собран на [Form](https://b24-ui.bx-shef.by/raw/docs/components/form.md): форма входа для внешнего приложения или личного кабинета. Её кладут прямо на страницу или в [PageCard](https://b24-ui.bx-shef.by/raw/docs/components/page-card.md).

```vue [AuthFormExample.vue]
<script setup lang="ts">
import * as z from 'zod'
import type { FormSubmitEvent, AuthFormField } from '@bxshefby/b24ui-nuxt'

const toast = useToast()

const fields: AuthFormField[] = [{
  name: 'email',
  type: 'email',
  label: 'Эл. почта',
  placeholder: 'Введите эл. почту',
  required: true
}, {
  name: 'password',
  label: 'Пароль',
  type: 'password',
  placeholder: 'Введите пароль',
  required: true
}, {
  name: 'remember',
  label: 'Запомнить меня',
  type: 'checkbox'
}]

const providers = [{
  label: 'Битрикс24',
  icon: 'i-bx24-common-service-bitrix24',
  onClick: () => {
    toast.add({ title: 'Битрикс24', description: 'Вход через Битрикс24' })
  }
}, {
  label: 'Яндекс',
  icon: 'i-bx24-common-service-yandex',
  onClick: () => {
    toast.add({ title: 'Яндекс', description: 'Вход через Яндекс ID' })
  }
}]

const schema = z.object({
  email: z.email('Неверный адрес почты'),
  password: z.string('Введите пароль').min(8, 'Не короче 8 символов')
})

type Schema = z.output<typeof schema>

function onSubmit(payload: FormSubmitEvent<Schema>) {
  console.log('Submitted', payload)
}
</script>

<template>
  <div class="flex flex-col items-center justify-center gap-4 p-4">
    <B24PageCard class="w-full max-w-md">
      <B24AuthForm
        :schema="schema"
        title="Вход"
        description="Введите данные, чтобы войти в аккаунт."
        icon="i-bx24-outline-person"
        :fields="fields"
        :providers="providers"
        @submit="onSubmit"
      />
    </B24PageCard>
  </div>
</template>
```

### Поля

Форма строится по пропсу `fields`, состояние она хранит сама.

Пропс `fields` — массив объектов со свойствами:

- `name: string`
- `type: 'checkbox' | 'select' | 'otp' | 'InputHTMLAttributes['type']'`

Свойство `type` выбирает поле и его пропсы: `checkbox` — пропсы [Checkbox](https://b24-ui.bx-shef.by/raw/docs/components/checkbox.md#props), `select` — [SelectMenu](https://b24-ui.bx-shef.by/raw/docs/components/select-menu.md#props), `otp` — [PinInput](https://b24-ui.bx-shef.by/raw/docs/components/pin-input.md#props), остальные типы — [Input](https://b24-ui.bx-shef.by/raw/docs/components/input.md#props).

Каждому полю можно передать и любой пропс [FormField](https://b24-ui.bx-shef.by/raw/docs/components/form-field.md#props).

```vue
<script setup lang="ts">
import type { AuthFormField } from '@bxshefby/b24ui-nuxt'

const fields = ref<AuthFormField[]>([
  {
    name: "email",
    type: "email",
    label: "Эл. почта",
    placeholder: "Введите эл. почту",
    required: true
  },
  {
    name: "password",
    type: "password",
    label: "Пароль",
    placeholder: "Введите пароль",
    required: true
  },
  {
    name: "city",
    type: "select",
    label: "Город",
    placeholder: "Выберите город",
    items: [
      {
        label: "Минск",
        value: "minsk"
      },
      {
        label: "Москва",
        value: "moscow"
      },
      {
        label: "Алматы",
        value: "almaty"
      },
      {
        label: "Ташкент",
        value: "tashkent"
      }
    ]
  },
  {
    name: "otp",
    type: "otp",
    label: "Код из СМС",
    length: 6,
    placeholder: "○"
  },
  {
    name: "remember",
    type: "checkbox",
    label: "Запомнить меня",
    description: "Вход сохранится на 30 дней."
  }
])
</script>

<template>
  <B24AuthForm :fields="fields" class="max-w-sm" />
</template>
```

### Заголовок

Пропс `title` задаёт заголовок формы.

```vue
<script setup lang="ts">
import type { AuthFormField } from '@bxshefby/b24ui-nuxt'

const fields = ref<AuthFormField[]>([
  {
    name: "email",
    type: "text",
    label: "Эл. почта"
  },
  {
    name: "password",
    type: "password",
    label: "Пароль"
  }
])
</script>

<template>
  <B24AuthForm title="Вход" :fields="fields" class="max-w-md" />
</template>
```

> [!TIP]
> Заголовок по умолчанию отрисовывается как `div`. Чтобы сделать его заголовком, передайте в пропс `as` объект, например `:as="{ title: 'h3' }"`. Корневой элемент задаётся так же: `:as="{ root: 'section', title: 'h3' }"`.

### Описание

Пропс `description` задаёт пояснение под заголовком.

```vue
<script setup lang="ts">
import type { AuthFormField } from '@bxshefby/b24ui-nuxt'

const fields = ref<AuthFormField[]>([
  {
    name: "email",
    type: "text",
    label: "Эл. почта"
  },
  {
    name: "password",
    type: "password",
    label: "Пароль"
  }
])
</script>

<template>
  <B24AuthForm title="Вход" description="Введите данные, чтобы войти в аккаунт." :fields="fields" class="max-w-md" />
</template>
```

### Иконка

Пропс `icon` задаёт иконку над заголовком.

```vue
<script setup lang="ts">
import type { AuthFormField } from '@bxshefby/b24ui-nuxt'

const fields = ref<AuthFormField[]>([
  {
    name: "email",
    type: "text",
    label: "Эл. почта"
  },
  {
    name: "password",
    type: "password",
    label: "Пароль"
  }
])
</script>

<template>
  <B24AuthForm title="Вход" description="Введите данные, чтобы войти в аккаунт." icon="i-bx24-outline-person" :fields="fields" class="max-w-md" />
</template>
```

### Сервисы входа

Пропс `providers` добавляет кнопки входа через сервисы. Каждой кнопке можно передать любой пропс [Button](https://b24-ui.bx-shef.by/raw/docs/components/button.md): `color`, `to` и другие.

```vue
<script setup lang="ts">
import type { ButtonProps, AuthFormField } from '@bxshefby/b24ui-nuxt'

const providers = ref<ButtonProps[]>([
  {
    label: "Битрикс24",
    icon: "i-bx24-common-service-bitrix24"
  },
  {
    label: "Яндекс",
    icon: "i-bx24-common-service-yandex"
  }
])
const fields = ref<AuthFormField[]>([
  {
    name: "email",
    type: "text",
    label: "Эл. почта"
  },
  {
    name: "password",
    type: "password",
    label: "Пароль"
  }
])
</script>

<template>
  <B24AuthForm title="Вход" description="Введите данные, чтобы войти в аккаунт." icon="i-bx24-outline-person" :providers="providers" :fields="fields" class="max-w-md" />
</template>
```

### Разделитель

Пропс `separator` меняет [Separator](https://b24-ui.bx-shef.by/raw/docs/components/separator.md) между кнопками сервисов и полями. По умолчанию — подпись из локали (`или` в русской).

```vue
<script setup lang="ts">
import type { ButtonProps, AuthFormField } from '@bxshefby/b24ui-nuxt'

const providers = ref<ButtonProps[]>([
  {
    label: "Битрикс24",
    icon: "i-bx24-common-service-bitrix24"
  },
  {
    label: "Яндекс",
    icon: "i-bx24-common-service-yandex"
  }
])
const fields = ref<AuthFormField[]>([
  {
    name: "email",
    type: "text",
    label: "Эл. почта"
  },
  {
    name: "password",
    type: "password",
    label: "Пароль"
  }
])
</script>

<template>
  <B24AuthForm title="Вход" description="Введите данные, чтобы войти в аккаунт." icon="i-bx24-outline-person" :providers="providers" :fields="fields" class="max-w-md" separator="Или по почте" />
</template>
```

Разделителю можно передать любой пропс [Separator](https://b24-ui.bx-shef.by/raw/docs/components/separator.md#props).

```vue
<script setup lang="ts">
import type { ButtonProps, AuthFormField } from '@bxshefby/b24ui-nuxt'

const providers = ref<ButtonProps[]>([
  {
    label: "Битрикс24",
    icon: "i-bx24-common-service-bitrix24"
  },
  {
    label: "Яндекс",
    icon: "i-bx24-common-service-yandex"
  }
])
const fields = ref<AuthFormField[]>([
  {
    name: "email",
    type: "text",
    label: "Эл. почта"
  },
  {
    name: "password",
    type: "password",
    label: "Пароль"
  }
])
</script>

<template>
  <B24AuthForm title="Вход" description="Введите данные, чтобы войти в аккаунт." icon="i-bx24-outline-person" :providers="providers" :fields="fields" class="max-w-md" :separator="{
  icon: 'i-bx24-outline-person'
}" />
</template>
```

### Кнопка отправки

Пропс `submit` меняет кнопку отправки формы. Ей можно передать любой пропс [Button](https://b24-ui.bx-shef.by/raw/docs/components/button.md), кроме ссылочных: `color`, `size` и другие.

```vue
<script setup lang="ts">
import type { AuthFormField } from '@bxshefby/b24ui-nuxt'

const fields = ref<AuthFormField[]>([
  {
    name: "email",
    type: "text",
    label: "Эл. почта"
  },
  {
    name: "password",
    type: "password",
    label: "Пароль"
  }
])
</script>

<template>
  <B24AuthForm title="Вход" description="Введите данные, чтобы войти в аккаунт." icon="i-bx24-outline-person" :fields="fields" class="max-w-md" :submit="{
  label: 'Войти',
  color: 'air-primary-success'
}" />
</template>
```

## Примеры

### На странице

Оберните `AuthForm` в [PageCard](https://b24-ui.bx-shef.by/raw/docs/components/page-card.md), чтобы показать её, например, на странице `login.vue`.

```vue [AuthFormPageExample.vue]
<script setup lang="ts">
import * as z from 'zod'
import type { FormSubmitEvent, AuthFormField } from '@bxshefby/b24ui-nuxt'

const toast = useToast()

const fields: AuthFormField[] = [{
  name: 'email',
  type: 'email',
  label: 'Эл. почта',
  placeholder: 'Введите эл. почту',
  required: true
}, {
  name: 'password',
  label: 'Пароль',
  type: 'password',
  placeholder: 'Введите пароль',
  required: true
}, {
  name: 'remember',
  label: 'Запомнить меня',
  type: 'checkbox'
}]

const providers = [{
  label: 'Битрикс24',
  icon: 'i-bx24-common-service-bitrix24',
  onClick: () => {
    toast.add({ title: 'Битрикс24', description: 'Вход через Битрикс24' })
  }
}, {
  label: 'Яндекс',
  icon: 'i-bx24-common-service-yandex',
  onClick: () => {
    toast.add({ title: 'Яндекс', description: 'Вход через Яндекс ID' })
  }
}]

const schema = z.object({
  email: z.email('Неверный адрес почты'),
  password: z.string('Введите пароль').min(8, 'Не короче 8 символов')
})

type Schema = z.output<typeof schema>

function onSubmit(payload: FormSubmitEvent<Schema>) {
  console.log('Submitted', payload)
}
</script>

<template>
  <div class="flex flex-col items-center justify-center gap-4 p-4">
    <B24PageCard class="w-full max-w-md">
      <B24AuthForm
        :schema="schema"
        :fields="fields"
        :providers="providers"
        title="С возвращением!"
        icon="i-bx24-outline-lock-l"
        @submit="onSubmit"
      >
        <template #description>
          Нет аккаунта? <B24Link to="#" class="text-(--ui-color-accent-main-primary) font-(--ui-font-weight-medium)">Зарегистрируйтесь</B24Link>.
        </template>
        <template #password-hint>
          <B24Link to="#" class="text-(--ui-color-accent-main-primary) font-(--ui-font-weight-medium)" tabindex="-1">Забыли пароль?</B24Link>
        </template>
        <template #validation>
          <B24Alert color="air-primary-alert" icon="i-bx24-outline-info-circle" title="Не удалось войти" />
        </template>
        <template #footer>
          Входя, вы принимаете <B24Link to="#" class="text-(--ui-color-accent-main-primary) font-(--ui-font-weight-medium)">условия использования</B24Link>.
        </template>
      </B24AuthForm>
    </B24PageCard>
  </div>
</template>
```

## API

### Пропсы

```ts
/**
 * Props for the AuthForm component
 */
interface AuthFormProps {
  /**
   * The element or component this component should render as.
   * @default 'div'
   */
  as?: any;
  /**
   * The icon displayed above the title.
   */
  icon?: IconProp | undefined;
  title?: string | undefined;
  description?: string | undefined;
  fields?: F[] | undefined;
  /**
   * Display a list of Button under the description.
   * `{ color: 'air-secondary-no-accent', block: true }`
   */
  providers?: ButtonProps[] | undefined;
  /**
   * The text displayed in the separator.
   * @default t('authForm.separator')
   */
  separator?: string | SeparatorProps | undefined;
  /**
   * Display a submit button at the bottom of the form.
   * `{ label: 'Continue', color: 'air-primary', block: true }`
   */
  submit?: Omit<ButtonProps, LinkPropsKeys> | undefined;
  schema?: T | undefined;
  validate?: (state: Partial<InferInput<T>>): FormError<string>[] | Promise<FormError<string>[]> | undefined;
  validateOn?: FormInputEvents[] | undefined;
  validateOnInputDelay?: number | undefined;
  disabled?: boolean | undefined;
  loading?: boolean | undefined;
  loadingAuto?: boolean | undefined;
  b24ui?: { root?: SlotClass; header?: SlotClass; leading?: SlotClass; leadingIcon?: SlotClass; title?: SlotClass; description?: SlotClass; body?: SlotClass; providers?: SlotClass; checkbox?: SlotClass; select?: SlotClass; password?: SlotClass; otp?: SlotClass; input?: SlotClass; separator?: SlotClass; form?: SlotClass; footer?: SlotClass; } | undefined;
  name?: string | undefined;
  autocomplete?: string | undefined;
  acceptcharset?: string | undefined;
  action?: string | undefined;
  enctype?: string | undefined;
  method?: string | undefined;
  novalidate?: false | true | "true" | "false" | undefined;
  target?: string | undefined;
}
```

> [!NOTE]
> See: https://developer.mozilla.org/ru/docs/Web/HTML/Element/form#attributes
> Компонент принимает и все атрибуты HTML-элемента `<form>`.

### Слоты

```ts
/**
 * Slots for the AuthForm component
 */
interface AuthFormSlots {
  header(): any;
  leading(): any;
  title(): any;
  description(): any;
  providers(): any;
  separator(): any;
  validation(): any;
  submit(): any;
  footer(): any;
}
```

### События

```ts
/**
 * Emitted events for the AuthForm component
 */
interface AuthFormEmits {
  submit: (payload: [payload: FormSubmitEvent<InferOutput<T>>]) => void;
}
```

### Доступ через ref

Типизированный экземпляр компонента (с `formRef` и `state`) доступен через [`useTemplateRef`](https://vuejs.org/api/composition-api-helpers.html#usetemplateref). Например, в отдельной форме сброса пароля:

```vue
<script setup lang="ts">
const authForm = useTemplateRef('authForm')
</script>

<template>
  <B24AuthForm ref="authForm" />
</template>
```

Доступны свойства:

| Имя | Тип |
| --- | --- |
| `formRef` | `Ref<HTMLFormElement \| null>` |
| `state` | `Reactive<FormStateType>` |

## Тема

```ts [app.config.ts]
export default defineAppConfig({
  b24ui: {
    authForm: {
      slots: {
        root: 'w-full space-y-6',
        header: 'flex flex-col text-center',
        leading: 'mb-2',
        leadingIcon: 'size-8 shrink-0 inline-block text-(--ui-color-design-plain-content-icon)',
        title: 'text-(length:--ui-font-size-2xl)/[normal] text-pretty font-(--ui-font-weight-semi-bold) text-label',
        description: 'mt-1 text-(length:--ui-font-size-lg)/[normal] text-pretty text-description',
        body: 'gap-y-6 flex flex-col',
        providers: 'space-y-3',
        checkbox: '',
        select: 'w-full',
        password: 'w-full',
        otp: 'w-full',
        input: 'w-full',
        separator: '',
        form: 'space-y-5',
        footer: 'text-(length:--ui-font-size-sm) text-center text-legend mt-2'
      }
    }
  }
})
```

## Sitemap

See the full [sitemap](/sitemap.md) for all pages.
