---
title: "Toast"
description: "Короткое сообщение, которое сообщает пользователю информацию или результат действия."
canonical_url: "https://b24-ui.bx-shef.by/docs/components/toast"
---
# Toast

> Короткое сообщение, которое сообщает пользователю информацию или результат действия.

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

Композабл [useToast](https://b24-ui.bx-shef.by/raw/docs/composables/use-toast.md) показывает уведомление в приложении.

```vue [ToastExample.vue]
<script setup lang="ts">
import PlusLIcon from '@bitrix24/b24icons-vue/outline/PlusLIcon'
import CalendarWithSlotsIcon from '@bitrix24/b24icons-vue/outline/CalendarWithSlotsIcon'

const toast = useToast()

function addToCalendar() {
  const eventDate = new Date(Date.now() + Math.random() * 31536000000)
  const formattedDate = eventDate.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })

  toast.add({
    title: 'Событие добавлено в календарь',
    description: `Это событие запланировано на ${formattedDate}.`,
    icon: CalendarWithSlotsIcon
  })
}
</script>

<template>
  <B24Button label="Добавить в календарь" :icon="PlusLIcon" @click="addToCalendar" />
</template>
```

> [!WARNING]
> Оберните приложение в компонент [`App`](https://b24-ui.bx-shef.by/raw/docs/components/app.md): он использует наш компонент [`Toaster`](https://github.com/bitrix24/b24ui/blob/main/src/runtime/components/Toaster.vue), а тот — компонент [`ToastProvider`](https://reka-ui.com/docs/components/toast#provider) из Reka UI.

> [!TIP]
> See: /docs/components/app/#props
> Пропс `toaster` компонента `App` показывает, как настроить Toaster глобально.

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

Поле `title` в методе `toast.add` показывает заголовок.

```vue [ToastTitleExample.vue]
<script setup lang="ts">
const props = defineProps<{
  title: string
}>()

const toast = useToast()

function showToast() {
  toast.add(props)
}
</script>

<template>
  <B24Button label="Показать уведомление" @click="showToast" />
</template>
```

### Описание

Поле `description` в методе `toast.add` показывает описание.

```vue [ToastDescriptionExample.vue]
<script setup lang="ts">
const props = defineProps<{
  title: string
  description: string
}>()

const toast = useToast()

function showToast() {
  toast.add(props)
}
</script>

<template>
  <B24Button label="Показать уведомление" @click="showToast" />
</template>
```

### Иконка

Поле `icon` в методе `toast.add` показывает [иконку](https://bitrix24.github.io/b24icons/icons/).

```vue [ToastIconExample.vue]
<script setup lang="ts">
import CopilotAiIcon from '@bitrix24/b24icons-vue/main/CopilotAiIcon'

const toast = useToast()

function showToast() {
  toast.add({
    title: 'Ой! Что-то пошло не так.',
    description: 'Возникла проблема с вашим запросом.',
    icon: CopilotAiIcon
  })
}
</script>

<template>
  <B24Button label="Показать уведомление" @click="showToast" />
</template>
```

### Аватар

Поле `avatar` в методе `toast.add` показывает [Avatar](https://b24-ui.bx-shef.by/raw/docs/components/avatar.md).

```vue [ToastAvatarExample.vue]
<script setup lang="ts">
const toast = useToast()

function showToast() {
  toast.add({
    title: 'Расчёт показателей завершён',
    description: 'Нужна ли вам ещё какая-нибудь помощь?',
    avatar: { src: '/b24ui/avatar/assistant.png' }
  })
}
</script>

<template>
  <B24Button label="Показать уведомление" @click="showToast" />
</template>
```

### Цвет

Поле `color` в методе `toast.add` меняет цвет уведомления.

```vue [ToastColorExample.vue]
<script setup lang="ts">
import type { ToastProps } from '@bxshefby/b24ui-nuxt'
import CopilotAiIcon from '@bitrix24/b24icons-vue/main/CopilotAiIcon'

const props = defineProps<{
  color: ToastProps['color']
}>()

const toast = useToast()

function showToast() {
  toast.add({
    title: 'Ой! Что-то пошло не так.',
    description: 'Возникла проблема с вашим запросом.',
    icon: CopilotAiIcon,
    color: props.color
  })
}
</script>

<template>
  <B24Button label="Показать уведомление" @click="showToast" />
</template>
```

### Закрытие

Поле `close` настраивает кнопку закрытия [Button](https://b24-ui.bx-shef.by/raw/docs/components/button.md) или скрывает её (значение `false`).

```vue [ToastCloseExample.vue]
<script setup lang="ts">
import CopilotAiIcon from '@bitrix24/b24icons-vue/main/CopilotAiIcon'

const toast = useToast()

function showToast() {
  toast.add({
    title: 'Ой! Что-то пошло не так.',
    description: 'Возникла проблема с вашим запросом.',
    icon: CopilotAiIcon,
    close: {
      color: 'air-primary-copilot',
      class: 'rounded-full'
    }
  })
}
</script>

<template>
  <B24Button label="Показать уведомление" @click="showToast" />
</template>
```

### Иконка закрытия

Поле `closeIcon` меняет [иконку](https://bitrix24.github.io/b24icons/icons/) кнопки закрытия.

```vue [ToastCloseIconExample.vue]
<script setup lang="ts">
import ArrowToTheRightIcon from '@bitrix24/b24icons-vue/actions/ArrowToTheRightIcon'

const toast = useToast()

function showToast() {
  toast.add({
    title: 'Ой! Что-то пошло не так.',
    description: 'Возникла проблема с вашим запросом.',
    closeIcon: ArrowToTheRightIcon
  })
}
</script>

<template>
  <B24Button label="Показать уведомление" @click="showToast" />
</template>
```

### Действия

Поле `actions` добавляет уведомлению кнопки действий [Button](https://b24-ui.bx-shef.by/raw/docs/components/button.md).

```vue [ToastActionsExample.vue]
<script setup lang="ts">
import Refresh9Icon from '@bitrix24/b24icons-vue/crm/Refresh9Icon'

const toast = useToast()

const props = defineProps<{
  description: string
}>()

function showToast() {
  toast.add({
    title: 'Ой! Что-то пошло не так.',
    description: props.description,
    actions: [{
      icon: Refresh9Icon,
      label: 'Повторить',
      color: 'air-secondary-accent-2',
      onClick: (e) => {
        e?.stopPropagation()
      }
    }]
  })
}
</script>

<template>
  <B24Button label="Показать уведомление" @click="showToast" />
</template>
```

### Длительность

Поле `duration` в методе `toast.add` задаёт, как долго уведомление остаётся на экране (в миллисекундах). По умолчанию `5000`.

> [!TIP]
> Значение `0` в поле `duration` оставляет уведомление открытым, пока его не закроют вручную.

```vue [ToastDurationExample.vue]
<script setup lang="ts">
const toast = useToast()

const props = defineProps<{
  duration: number
}>()

function showToast() {
  toast.add({
    title: 'Ой! Что-то пошло не так.',
    description: 'Возникла проблема с вашим запросом.',
    duration: props.duration
  })
}
</script>

<template>
  <B24Button label="Показать уведомление" @click="showToast" />
</template>
```

### Прогресс

Поле `progress` настраивает полосу [Progress](https://b24-ui.bx-shef.by/raw/docs/components/progress.md) или скрывает её (значение `false`).

> [!TIP]
> По умолчанию полоса Progress наследует цвет уведомления, но его можно переопределить полем `progress.color`.

```vue [ToastProgressExample.vue]
<script setup lang="ts">
import CopilotAiIcon from '@bitrix24/b24icons-vue/main/CopilotAiIcon'

const toast = useToast()

function showToast() {
  toast.add({
    title: 'Ой! Что-то пошло не так.',
    description: 'Возникла проблема с вашим запросом.',
    icon: CopilotAiIcon,
    progress: false
  })
}
</script>

<template>
  <B24Button label="Показать уведомление" @click="showToast" />
</template>
```

### Ориентация

Поле `orientation` в методе `toast.add` меняет ориентацию уведомления.

```vue [ToastOrientationExample.vue]
<script setup lang="ts">
import Refresh9Icon from '@bitrix24/b24icons-vue/crm/Refresh9Icon'

const toast = useToast()

const props = defineProps<{
  orientation: 'horizontal' | 'vertical'
}>()

function showToast() {
  toast.add({
    title: 'Ой! Что-то пошло не так.',
    orientation: props.orientation,
    actions: [{
      icon: Refresh9Icon,
      label: 'Повторить',
      color: 'air-secondary-accent-2',
      onClick: (e) => {
        e?.stopPropagation()
      }
    }]
  })
}
</script>

<template>
  <B24Button label="Показать уведомление" @click="showToast" />
</template>
```

## Примеры

> [!NOTE]
> See: /docs/components/app/
> Bitrix24 UI предоставляет компонент **App**, который оборачивает приложение и задаёт глобальные настройки.

### Глобальная позиция

Пропс `toaster.position` компонента [App](https://b24-ui.bx-shef.by/raw/docs/components/app.md#props) меняет позицию уведомлений.

```vue [app.vue]
<script setup lang="ts">
const toaster = { position: 'bottom-right' }
</script>

<template>
  <B24App :toaster="toaster">
    <NuxtPage />
  </B24App>
</template>
```

```vue [ToastExample.vue]
<script setup lang="ts">
import PlusLIcon from '@bitrix24/b24icons-vue/outline/PlusLIcon'
import CalendarWithSlotsIcon from '@bitrix24/b24icons-vue/outline/CalendarWithSlotsIcon'

const toast = useToast()

function addToCalendar() {
  const eventDate = new Date(Date.now() + Math.random() * 31536000000)
  const formattedDate = eventDate.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })

  toast.add({
    title: 'Событие добавлено в календарь',
    description: `Это событие запланировано на ${formattedDate}.`,
    icon: CalendarWithSlotsIcon
  })
}
</script>

<template>
  <B24Button label="Добавить в календарь" :icon="PlusLIcon" @click="addToCalendar" />
</template>
```

### Глобальная длительность

Пропс `toaster.duration` компонента [App](https://b24-ui.bx-shef.by/raw/docs/components/app.md#props) меняет длительность уведомлений.

```vue [app.vue]
<script setup lang="ts">
const toaster = { duration: 5000 }
</script>

<template>
  <B24App :toaster="toaster">
    <NuxtPage />
  </B24App>
</template>
```

```vue [ToastExample.vue]
<script setup lang="ts">
import PlusLIcon from '@bitrix24/b24icons-vue/outline/PlusLIcon'
import CalendarWithSlotsIcon from '@bitrix24/b24icons-vue/outline/CalendarWithSlotsIcon'

const toast = useToast()

function addToCalendar() {
  const eventDate = new Date(Date.now() + Math.random() * 31536000000)
  const formattedDate = eventDate.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })

  toast.add({
    title: 'Событие добавлено в календарь',
    description: `Это событие запланировано на ${formattedDate}.`,
    icon: CalendarWithSlotsIcon
  })
}
</script>

<template>
  <B24Button label="Добавить в календарь" :icon="PlusLIcon" @click="addToCalendar" />
</template>
```

### Глобальный максимум

Пропс `toaster.max` компонента [App](https://b24-ui.bx-shef.by/raw/docs/components/app.md#props) меняет максимальное число уведомлений, показываемых одновременно.

```vue [app.vue]
<script setup lang="ts">
const toaster = { max: 3 }
</script>

<template>
  <B24App :toaster="toaster">
    <NuxtPage />
  </B24App>
</template>
```

```vue [ToastExample.vue]
<script setup lang="ts">
import PlusLIcon from '@bitrix24/b24icons-vue/outline/PlusLIcon'
import CalendarWithSlotsIcon from '@bitrix24/b24icons-vue/outline/CalendarWithSlotsIcon'

const toast = useToast()

function addToCalendar() {
  const eventDate = new Date(Date.now() + Math.random() * 31536000000)
  const formattedDate = eventDate.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })

  toast.add({
    title: 'Событие добавлено в календарь',
    description: `Это событие запланировано на ${formattedDate}.`,
    icon: CalendarWithSlotsIcon
  })
}
</script>

<template>
  <B24Button label="Добавить в календарь" :icon="PlusLIcon" @click="addToCalendar" />
</template>
```

### Стопка уведомлений

Пропс `toaster.expand` со значением `false` в компоненте [App](https://b24-ui.bx-shef.by/raw/docs/components/app.md#props) показывает уведомления стопкой (по мотивам [Sonner](https://sonner.emilkowal.ski/)).

```vue [app.vue]
<script setup lang="ts">
const toaster = { expand: false }
</script>

<template>
  <B24App :toaster="toaster">
    <NuxtPage />
  </B24App>
</template>
```

> [!TIP]
> При наведении на уведомления стопка разворачивается, а таймер уведомлений ставится на паузу.

```vue [ToastExample.vue]
<script setup lang="ts">
import PlusLIcon from '@bitrix24/b24icons-vue/outline/PlusLIcon'
import CalendarWithSlotsIcon from '@bitrix24/b24icons-vue/outline/CalendarWithSlotsIcon'

const toast = useToast()

function addToCalendar() {
  const eventDate = new Date(Date.now() + Math.random() * 31536000000)
  const formattedDate = eventDate.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })

  toast.add({
    title: 'Событие добавлено в календарь',
    description: `Это событие запланировано на ${formattedDate}.`,
    icon: CalendarWithSlotsIcon
  })
}
</script>

<template>
  <B24Button label="Добавить в календарь" :icon="PlusLIcon" @click="addToCalendar" />
</template>
```

### Дедупликация уведомлений

Если вызвать `toast.add` с уже существующим `id`, существующее уведомление пульсирует, а дубликат не создаётся.

```vue [ToastDuplicateExample.vue]
<script setup lang="ts">
import CircleCrossIcon from '@bitrix24/b24icons-vue/outline/CircleCrossIcon'

const toast = useToast()

function showToast() {
  toast.add({
    id: 'copy',
    title: 'Скопировано в буфер обмена',
    icon: CircleCrossIcon,
    duration: 0
  })
}
</script>

<template>
  <B24Button label="Показать уведомление" @click="showToast" />
</template>
```

### С обратным вызовом

Поле `onUpdateOpen` задаёт обратный вызов, который выполняется при закрытии уведомления (по истечении времени или по действию пользователя).

```vue [ToastCallbackExample.vue]
<script setup lang="ts">
import UploadIcon from '@bitrix24/b24icons-vue/outline/UploadIcon'
import CheckLIcon from '@bitrix24/b24icons-vue/outline/CheckLIcon'

const toast = useToast()

function showToast() {
  const t = toast.add({
    'title': 'Uploading file...',
    'description': 'Your file is being uploaded.',
    'icon': UploadIcon,
    'duration': 3000,
    'onUpdate:open': (open: boolean) => {
      if (open) {
        return
      }

      toast.update(t.id, {
        'title': 'File uploaded!',
        'description': 'Файл успешно загружен.',
        'icon': CheckLIcon,
        'color': 'air-primary-success',
        'onUpdate:open': undefined
      })
    }
  })
}
</script>

<template>
  <B24Button label="Показать уведомление" @click="showToast" />
</template>
```

### С промисом `Soon`

Метод `toast.promise` показывает уведомление загрузки, которое обновляется, когда промис выполнен или отклонён.

```vue [ToastPromiseExample.vue]
<script setup lang="ts">
import CheckLIcon from '@bitrix24/b24icons-vue/outline/CheckLIcon'
import CrossMIcon from '@bitrix24/b24icons-vue/outline/CrossMIcon'

const toast = useToast()

function upload() {
  return new Promise<string>(resolve => setTimeout(() => resolve('report.pdf'), 2000))
}

function showToast() {
  toast.promise(upload(), {
    loading: { title: 'Загрузка файла...', description: 'Файл загружается.' },
    success: name => ({
      title: 'Файл загружен!',
      description: `Файл ${name} успешно загружен.`,
      icon: CheckLIcon,
      color: 'air-primary-success'
    }),
    error: {
      title: 'Не удалось загрузить',
      description: 'Что-то пошло не так, попробуйте ещё раз.',
      icon: CrossMIcon,
      color: 'air-primary-alert'
    }
  })
}
</script>

<template>
  <B24Button label="Показать уведомление" @click="showToast" />
</template>
```

> [!WARNING]
> Не показывайте пользователю внутренние сообщения об ошибках бэкенда: вместо `error: e => e.message` задавайте понятный текст.

### С HTML-содержимым

[Функция отрисовки `h()`](https://vuejs.org/api/render-function.html#h) в полях `title` или `description` отрисовывает HTML-элементы или компоненты Vue с произвольным оформлением.

```vue [ToastHtmlExample.vue]
<script setup lang="ts">
import TrashcanIcon from '@bitrix24/b24icons-vue/solid/TrashcanIcon'

const toast = useToast()

function showToast() {
  toast.add({
    title: h('span', {}, [
      'Элемент ',
      h('span', { class: 'text-(--ui-color-accent-main-primary) font-bold' }, '#15'),
      ' удалён'
    ]),
    description: h('span', {}, [
      'Вы успешно удалили элемент из своего ',
      h('span', { class: 'font-bold' }, 'аккаунта'),
      '.'
    ]),
    icon: TrashcanIcon
  })
}
</script>

<template>
  <B24Button label="Показать уведомление" @click="showToast" />
</template>
```

## API

### Пропсы

```ts
/**
 * Props for the Toast component
 */
interface ToastProps {
  /**
   * The element or component this component should render as.
   * @default 'li'
   */
  as?: any;
  title?: string | VNode<RendererNode, RendererElement, { [key: string]: any; }> | (): VNode<RendererNode, RendererElement, { [key: string]: any; }> | undefined;
  description?: string | VNode<RendererNode, RendererElement, { [key: string]: any; }> | (): VNode<RendererNode, RendererElement, { [key: string]: any; }> | undefined;
  icon?: (props: HTMLAttributes & VNodeProps & {}, ctx: Omit<{ attrs: Attrs; slots: Readonly<InternalSlots>; emit: (event: string, ...args: any[]) => void; expose: <Exposed extends Record<string, any> = Record<...>>(exposed?: Exposed | undefined) => void; }, "expose">): any | undefined;
  avatar?: AvatarProps | undefined;
  /**
   * @default 'air-secondary-no-accent'
   */
  color?: "air-primary" | "air-primary-success" | "air-primary-alert" | "air-primary-warning" | "air-primary-copilot" | "air-secondary";
  /**
   * The orientation between the content and the actions
   * @default 'vertical'
   */
  orientation?: "vertical" | "horizontal" | undefined;
  /**
   * Display a close button to dismiss the toast.
   * `{ size: 'sm', color: 'air-tertiary' }`{lang="ts"}
   * @default true
   */
  close?: boolean | Omit<ButtonProps, LinkPropsKeys> | undefined;
  /**
   * The icon displayed in the close button.
   * @default icons.close
   */
  closeIcon?: (props: HTMLAttributes & VNodeProps & {}, ctx: Omit<{ attrs: Attrs; slots: Readonly<InternalSlots>; emit: (event: string, ...args: any[]) => void; expose: <Exposed extends Record<string, any> = Record<...>>(exposed?: Exposed | undefined) => void; }, "expose">): any | undefined;
  /**
   * Display a list of actions:
   * - under the title and description when orientation is `vertical`
   * - next to the close button when orientation is `horizontal`
   * `{ size: 'sm' }`{lang="ts"}
   */
  actions?: (ButtonProps & { closeOnClick?: boolean | undefined; })[] | undefined;
  /**
   * The time in milliseconds before the toast automatically closes. Overrides the global `toaster.duration`.
   * 
   * Set to `0` to keep the toast open until it's manually closed.
   * @default 5000
   */
  duration?: number | undefined;
  /**
   * Display a progress bar showing the toast's remaining duration.
   * `{ size: 'sm' }`{lang="ts"}
   * @default true
   */
  progress?: boolean | Pick<ProgressProps, "color" | "b24ui"> | undefined;
  b24ui?: { root?: SlotClass; wrapper?: SlotClass; title?: SlotClass; description?: SlotClass; icon?: SlotClass; avatar?: SlotClass; avatarSize?: SlotClass; actions?: SlotClass; progress?: SlotClass; close?: SlotClass; } | undefined;
  /**
   * The open state of the dialog when it is initially rendered. Use when you do not need to control its open state.
   */
  defaultOpen?: boolean | undefined;
  /**
   * The controlled open state of the dialog. Can be bind as `v-model:open`.
   */
  open?: boolean | undefined;
  /**
   * Control the sensitivity of the toast for accessibility purposes.
   * 
   * For toasts that are the result of a user action, choose `foreground`. Toasts generated from background tasks should use `background`.
   */
  type?: "foreground" | "background" | undefined;
}
```

### Слоты

```ts
/**
 * Slots for the Toast component
 */
interface ToastSlots {
  leading(): any;
  title(): any;
  description(): any;
  actions(): any;
  close(): any;
}
```

### События

```ts
/**
 * Emitted events for the Toast component
 */
interface ToastEmits {
  pause: (payload: []) => void;
  escapeKeyDown: (payload: [event: KeyboardEvent]) => void;
  resume: (payload: []) => void;
  swipeStart: (payload: [event: SwipeEvent]) => void;
  swipeMove: (payload: [event: SwipeEvent]) => void;
  swipeCancel: (payload: [event: SwipeEvent]) => void;
  swipeEnd: (payload: [event: SwipeEvent]) => void;
  update:open: (payload: [value: boolean]) => void;
}
```

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

При обращении к компоненту через ref в шаблоне доступно:

| Имя | Тип |
| --- | --- |
| `height` | `Ref<number>` |

## Тема

```ts [app.config.ts]
export default defineAppConfig({
  b24ui: {
    toast: {
      slots: {
        root: 'dark relative group overflow-hidden rounded-[8px] p-4 flex gap-4 focus-visible:outline-(length:--ui-design-outline-stroke-weight) focus-visible:outline-offset-2 focus-visible:outline-(--ui-color-design-outline-focused-stroke) font-[family-name:var(--ui-font-family-primary)] bg-(--ui-color-base-black-fixed)/80 text-(--ui-color-design-plain-na-focused-content) text-(length:--ui-font-size-sm) font-(--ui-font-weight-normal)',
        wrapper: 'w-0 flex-1 flex flex-col',
        title: 'font-(--ui-font-weight-medium)',
        description: '',
        icon: 'shrink-0 size-6 text-(--b24ui-border-color)',
        avatar: 'shrink-0',
        avatarSize: 'xl',
        actions: 'flex gap-1.5 shrink-0',
        progress: 'absolute inset-x-0 bottom-0',
        close: 'p-0 absolute top-2 right-2'
      },
      variants: {
        color: {
          'air-primary': {
            root: 'style-filled'
          },
          'air-primary-success': {
            root: 'style-filled-success'
          },
          'air-primary-alert': {
            root: 'style-filled-alert'
          },
          'air-primary-copilot': {
            root: 'style-filled-copilot'
          },
          'air-primary-warning': {
            root: 'style-filled-warning'
          },
          'air-secondary': {
            root: 'style-filled-inverted'
          },
          default: {
            root: 'style-old-default'
          },
          danger: {
            root: 'style-old-danger'
          },
          success: {
            root: 'style-old-success'
          },
          warning: {
            root: 'style-old-warning'
          },
          primary: {
            root: 'style-old-primary'
          },
          secondary: {
            root: 'style-old-secondary'
          },
          collab: {
            root: 'style-old-collab'
          },
          ai: {
            root: 'style-old-ai'
          }
        },
        orientation: {
          horizontal: {
            root: 'items-center',
            actions: 'items-center'
          },
          vertical: {
            root: 'items-center',
            actions: 'items-start mt-1'
          }
        },
        title: {
          true: {
            description: 'mt-1'
          }
        }
      },
      defaultVariants: {
        color: 'air-secondary'
      }
    }
  }
})
```

## Sitemap

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