v2.15.0

Input

Поле для ввода текста.

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

Директива v-model управляет значением Input.

<script setup lang="ts">
const value = ref('')
</script>

<template>
  <B24Input v-model="value" />
</template>
<script setup lang="ts">
import { ref } from 'vue'

const value = ref('')
</script>

<template>
  <B24Input v-model="value" />
</template>

Тип

Пропс type меняет тип поля ввода. По умолчанию text.

Некоторые типы реализованы отдельными компонентами, например Checkbox, Radio, InputNumber и другие, а часть оформлена стилями, как file.

<template>
  <B24Input type="file" />
</template>
Все доступные типы описаны на MDN Web Docs.

Плейсхолдер

Пропс placeholder задаёт текст плейсхолдера.

<template>
  <B24Input placeholder="Поиск..." />
</template>

Цвет

Пропс color меняет цвет кольца, когда Input в фокусе.

<template>
  <B24Input color="air-primary-warning" highlight placeholder="Поиск..." />
</template>
Пропс highlight здесь показывает состояние фокуса. Внутри компонента он включается при ошибке валидации.

Тег

Свойство tag показывает Badge поверх Input.

заметка
<template>
  <B24Input tag="заметка" color="air-primary-warning" highlight placeholder="Поиск..." />
</template>
Пропс highlight здесь показывает состояние фокуса. Внутри компонента он включается при ошибке валидации.

Свойство tagColor задаёт цвет Badge.

заметка
<template>
  <B24Input
    tag-color="air-secondary-alert"
    tag="заметка"
    color="air-primary-warning"
    highlight
    placeholder="Поиск..."
  />
</template>
Пропс highlight здесь показывает состояние фокуса. Внутри компонента он включается при ошибке валидации.

Размер

Пропс size меняет размер Input.

<template>
  <B24Input size="xl" placeholder="Поиск..." />
</template>

Иконка

Пропс icon показывает иконку внутри Input.

<script setup lang="ts">
import RocketIcon from '@bitrix24/b24icons-vue/main/RocketIcon'
</script>

<template>
  <B24Input :icon="RocketIcon" size="md" placeholder="Поиск..." />
</template>

Иконка справа

Пропс trailing-icon задаёт иконку справа.

<script setup lang="ts">
import RocketIcon from '@bitrix24/b24icons-vue/main/RocketIcon'
</script>

<template>
  <B24Input :trailing-icon="RocketIcon" placeholder="Введите email" size="md" />
</template>

Аватар

Пропс avatar показывает Avatar внутри Input.

<template>
  <B24Input
    :avatar="{
      src: '/b24ui/avatar/employee.png',
      loading: 'lazy'
    }"
    size="md"
    placeholder="Поиск..."
  />
</template>

Загрузка

Пропс loading показывает иконку загрузки в Input.

<template>
  <B24Input loading placeholder="Поиск..." />
</template>

Отключение

Пропс disabled отключает Input.

<template>
  <B24Input disabled placeholder="Поиск..." />
</template>

Без отступов

Пропс noPadding убирает отступы у Input.

<template>
  <B24Input no-padding highlight placeholder="Поиск..." />
</template>
Пропс highlight здесь показывает состояние фокуса.

Без границы

Пропс noBorder убирает у Input все границы (кольца).

<template>
  <B24Input no-border highlight placeholder="Поиск..." />
</template>
Пропс highlight здесь показывает, что состояния фокуса нет.

Подчёркивание

Пропс underline убирает у Input все границы (кольца), кроме нижней.

<template>
  <B24Input underline highlight placeholder="Поиск..." />
</template>
Пропс highlight здесь показывает состояние фокуса.

Скругление

Пропс rounded скругляет Input.

<template>
  <B24Input rounded highlight placeholder="Поиск..." />
</template>
Пропс highlight здесь показывает состояние фокуса.

Примеры

С кнопкой очистки

В слот #trailing можно поместить Button, который очищает Input.

<script setup lang="ts">
import CircleCrossIcon from '@bitrix24/b24icons-vue/outline/CircleCrossIcon'

const value = ref('Нажмите, чтобы очистить')
</script>

<template>
  <B24Input
    v-model="value"
    placeholder="Введите что-нибудь..."
    :b24ui="{ trailing: 'pe-1' }"
  >
    <template v-if="value?.length" #trailing>
      <B24Button
        size="sm"
        color="air-tertiary-no-accent"
        :icon="CircleCrossIcon"
        aria-label="Очистить поле"
        @click="value = ''"
      />
    </template>
  </B24Input>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import CircleCrossIcon from '@bitrix24/b24icons-vue/outline/CircleCrossIcon'

const value = ref('Нажмите, чтобы очистить')
</script>

<template>
  <B24Input
    v-model="value"
    placeholder="Введите что-нибудь..."
    :b24ui="{ trailing: 'pe-1' }"
  >
    <template v-if="value?.length" #trailing>
      <B24Button
        size="sm"
        color="air-tertiary-no-accent"
        :icon="CircleCrossIcon"
        aria-label="Очистить поле"
        @click="value = ''"
      />
    </template>
  </B24Input>
</template>

С кнопкой копирования

В слот #trailing можно поместить Button, который копирует значение в буфер обмена.

<script setup lang="ts">
import CopyIcon from '@bitrix24/b24icons-vue/outline/CopyIcon'
import CircleCheckIcon from '@bitrix24/b24icons-vue/outline/CircleCheckIcon'

import { useClipboard } from '@vueuse/core'

const value = ref('npx nuxt module add @bxshefby/b24ui-nuxt')

const { copy, copied } = useClipboard()
</script>

<template>
  <B24Input
    v-model="value"
    :b24ui="{ trailing: 'pe-0.5' }"
  >
    <template v-if="value?.length" #trailing>
      <B24Tooltip text="Копировать в буфер обмена" :content="{ side: 'right' }">
        <B24Button
          :b24ui="{
            leadingIcon: [copied ? 'text-(--ui-color-accent-main-success)' : 'text-(--ui-btn-color)']
          }"
          size="sm"
          color="air-tertiary-no-accent"
          :icon="copied ? CircleCheckIcon : CopyIcon"
          aria-label="Копировать в буфер обмена"
          @click="copy(value)"
        />
      </B24Tooltip>
    </template>
  </B24Input>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import CopyIcon from '@bitrix24/b24icons-vue/outline/CopyIcon'
import CircleCheckIcon from '@bitrix24/b24icons-vue/outline/CircleCheckIcon'

import { useClipboard } from '@vueuse/core'

const value = ref('npx nuxt module add @bxshefby/b24ui-nuxt')

const { copy, copied } = useClipboard()
</script>

<template>
  <B24Input
    v-model="value"
    :b24ui="{ trailing: 'pe-0.5' }"
  >
    <template v-if="value?.length" #trailing>
      <B24Tooltip text="Копировать в буфер обмена" :content="{ side: 'right' }">
        <B24Button
          :b24ui="{
            leadingIcon: [copied ? 'text-(--ui-color-accent-main-success)' : 'text-(--ui-btn-color)']
          }"
          size="sm"
          color="air-tertiary-no-accent"
          :icon="copied ? CircleCheckIcon : CopyIcon"
          aria-label="Копировать в буфер обмена"
          @click="copy(value)"
        />
      </B24Tooltip>
    </template>
  </B24Input>
</template>

С переключателем пароля

В слот #trailing можно поместить Button, который переключает видимость пароля.

<script setup lang="ts">
import ObserverIcon from '@bitrix24/b24icons-vue/outline/ObserverIcon'
import CrossedEyeIcon from '@bitrix24/b24icons-vue/outline/CrossedEyeIcon'

const show = ref(false)
const password = ref('')
</script>

<template>
  <B24Input
    v-model="password"
    placeholder="Пароль"
    :type="show ? 'text' : 'password'"
    :b24ui="{ trailing: 'pe-1' }"
  >
    <template #trailing>
      <B24Button
        size="sm"
        color="air-tertiary-no-accent"
        :icon="show ? CrossedEyeIcon : ObserverIcon"
        :aria-label="show ? 'Скрыть пароль' : 'Показать пароль'"
        :aria-pressed="show"
        aria-controls="password"
        @click="show = !show"
      />
    </template>
  </B24Input>
</template>

<style>
/* Скрываем кнопку показа пароля в Edge */
::-ms-reveal {
    display: none;
}
</style>
<script setup lang="ts">
import { ref } from 'vue'
import ObserverIcon from '@bitrix24/b24icons-vue/outline/ObserverIcon'
import CrossedEyeIcon from '@bitrix24/b24icons-vue/outline/CrossedEyeIcon'

const show = ref(false)
const password = ref('')
</script>

<template>
  <B24Input
    v-model="password"
    placeholder="Пароль"
    :type="show ? 'text' : 'password'"
    :b24ui="{ trailing: 'pe-1' }"
  >
    <template #trailing>
      <B24Button
        size="sm"
        color="air-tertiary-no-accent"
        :icon="show ? CrossedEyeIcon : ObserverIcon"
        :aria-label="show ? 'Скрыть пароль' : 'Показать пароль'"
        :aria-pressed="show"
        aria-controls="password"
        @click="show = !show"
      />
    </template>
  </B24Input>
</template>

<style>
/* Скрываем кнопку показа пароля в Edge */
::-ms-reveal {
    display: none;
}
</style>

С индикатором надёжности пароля

Компонент Progress показывает индикатор надёжности пароля.

Введите пароль. Must contain:

  • Минимум 8 символов — требование не выполнено
  • Минимум 1 цифра — требование не выполнено
  • Минимум 1 строчная буква — требование не выполнено
  • Минимум 1 заглавная буква — требование не выполнено
<script setup lang="ts">
import ObserverIcon from '@bitrix24/b24icons-vue/outline/ObserverIcon'
import CrossedEyeIcon from '@bitrix24/b24icons-vue/outline/CrossedEyeIcon'
import CircleCheckIcon from '@bitrix24/b24icons-vue/outline/CircleCheckIcon'
import CircleCrossIcon from '@bitrix24/b24icons-vue/outline/CircleCrossIcon'

const show = ref(false)
const password = ref('')

function checkStrength(str: string) {
  const requirements = [
    { regex: /.{8,}/, text: 'Минимум 8 символов' },
    { regex: /\d/, text: 'Минимум 1 цифра' },
    { regex: /[a-z]/, text: 'Минимум 1 строчная буква' },
    { regex: /[A-Z]/, text: 'Минимум 1 заглавная буква' }
  ]

  return requirements.map(req => ({ met: req.regex.test(str), text: req.text }))
}

const strength = computed(() => checkStrength(password.value))
const score = computed(() => strength.value.filter(req => req.met).length)

const color = computed(() => {
  if (score.value === 0) return 'air-primary'
  if (score.value <= 1) return 'air-primary-alert'
  if (score.value <= 2) return 'air-primary-warning'
  if (score.value === 3) return 'air-primary-warning'
  return 'success'
})

const text = computed(() => {
  if (score.value === 0) return 'Введите пароль'
  if (score.value <= 2) return 'Слабый пароль'
  if (score.value === 3) return 'Средний пароль'
  return 'Надёжный пароль'
})
</script>

<template>
  <div class="space-y-2">
    <B24FormField label="Пароль">
      <B24Input
        v-model="password"
        placeholder="Пароль"
        :color="color"
        :type="show ? 'text' : 'password'"
        :aria-invalid="score < 4"
        aria-describedby="password-strength"
        :b24ui="{ trailing: 'pe-1' }"
        class="w-full"
      >
        <template #trailing>
          <B24Button
            size="sm"
            color="air-tertiary-no-accent"
            :icon="show ? CrossedEyeIcon : ObserverIcon"
            :aria-label="show ? 'Скрыть пароль' : 'Показать пароль'"
            :aria-pressed="show"
            aria-controls="password"
            @click="show = !show"
          />
        </template>
      </B24Input>
    </B24FormField>

    <B24Progress
      :color="color"
      :indicator="text"
      :model-value="score"
      :max="4"
      size="sm"
    />

    <p id="password-strength" class="text-(length:--ui-font-size-sm) font-(--ui-font-weight-medium)">
      {{ text }}. Must contain:
    </p>

    <ul class="space-y-1" aria-label="Требования к паролю">
      <li
        v-for="(req, index) in strength"
        :key="index"
        class="flex items-center gap-0.5"
        :class="req.met ? 'text-(--ui-color-accent-main-success)' : 'text-label'"
      >
        <CircleCheckIcon v-if="req.met" class="size-4 shrink-0" />
        <CircleCrossIcon v-else class="size-4 shrink-0" />

        <span class="text-(length:--ui-font-size-xs) font-(--ui-font-weight-light)">
          {{ req.text }}
          <span class="sr-only">
            {{ req.met ? ' — требование выполнено' : ' — требование не выполнено' }}
          </span>
        </span>
      </li>
    </ul>
  </div>
</template>
<script setup lang="ts">
import { ref, computed } from 'vue'
import ObserverIcon from '@bitrix24/b24icons-vue/outline/ObserverIcon'
import CrossedEyeIcon from '@bitrix24/b24icons-vue/outline/CrossedEyeIcon'
import CircleCheckIcon from '@bitrix24/b24icons-vue/outline/CircleCheckIcon'
import CircleCrossIcon from '@bitrix24/b24icons-vue/outline/CircleCrossIcon'

const show = ref(false)
const password = ref('')

function checkStrength(str: string) {
  const requirements = [
    { regex: /.{8,}/, text: 'Минимум 8 символов' },
    { regex: /\d/, text: 'Минимум 1 цифра' },
    { regex: /[a-z]/, text: 'Минимум 1 строчная буква' },
    { regex: /[A-Z]/, text: 'Минимум 1 заглавная буква' }
  ]

  return requirements.map(req => ({ met: req.regex.test(str), text: req.text }))
}

const strength = computed(() => checkStrength(password.value))
const score = computed(() => strength.value.filter(req => req.met).length)

const color = computed(() => {
  if (score.value === 0) return 'air-primary'
  if (score.value <= 1) return 'air-primary-alert'
  if (score.value <= 2) return 'air-primary-warning'
  if (score.value === 3) return 'air-primary-warning'
  return 'success'
})

const text = computed(() => {
  if (score.value === 0) return 'Введите пароль'
  if (score.value <= 2) return 'Слабый пароль'
  if (score.value === 3) return 'Средний пароль'
  return 'Надёжный пароль'
})
</script>

<template>
  <div class="space-y-2">
    <B24FormField label="Пароль">
      <B24Input
        v-model="password"
        placeholder="Пароль"
        :color="color"
        :type="show ? 'text' : 'password'"
        :aria-invalid="score < 4"
        aria-describedby="password-strength"
        :b24ui="{ trailing: 'pe-1' }"
        class="w-full"
      >
        <template #trailing>
          <B24Button
            size="sm"
            color="air-tertiary-no-accent"
            :icon="show ? CrossedEyeIcon : ObserverIcon"
            :aria-label="show ? 'Скрыть пароль' : 'Показать пароль'"
            :aria-pressed="show"
            aria-controls="password"
            @click="show = !show"
          />
        </template>
      </B24Input>
    </B24FormField>

    <B24Progress
      :color="color"
      :indicator="text"
      :model-value="score"
      :max="4"
      size="sm"
    />

    <p id="password-strength" class="text-(length:--ui-font-size-sm) font-(--ui-font-weight-medium)">
      {{ text }}. Must contain:
    </p>

    <ul class="space-y-1" aria-label="Требования к паролю">
      <li
        v-for="(req, index) in strength"
        :key="index"
        class="flex items-center gap-0.5"
        :class="req.met ? 'text-(--ui-color-accent-main-success)' : 'text-label'"
      >
        <CircleCheckIcon v-if="req.met" class="size-4 shrink-0" />
        <CircleCrossIcon v-else class="size-4 shrink-0" />

        <span class="text-(length:--ui-font-size-xs) font-(--ui-font-weight-light)">
          {{ req.text }}
          <span class="sr-only">
            {{ req.met ? ' — требование выполнено' : ' — требование не выполнено' }}
          </span>
        </span>
      </li>
    </ul>
  </div>
</template>

С ограничением длины

Слот #trailing позволяет показать ограничение числа символов Input.

0/15
<script setup lang="ts">
const value = ref('')
const maxLength = 15
</script>

<template>
  <B24Input
    v-model="value"
    :maxlength="maxLength"
    aria-describedby="character-count"
    :b24ui="{ trailing: 'pointer-events-none' }"
  >
    <template #trailing>
      <div
        id="character-count"
        class="text-(length:--ui-font-size-xs)/(--ui-font-line-height-reset) text-description tabular-nums"
        aria-live="polite"
        role="status"
      >
        {{ value?.length }}/{{ maxLength }}
      </div>
    </template>
  </B24Input>
</template>
<script setup lang="ts">
import { ref } from 'vue'

const value = ref('')
const maxLength = 15
</script>

<template>
  <B24Input
    v-model="value"
    :maxlength="maxLength"
    aria-describedby="character-count"
    :b24ui="{ trailing: 'pointer-events-none' }"
  >
    <template #trailing>
      <div
        id="character-count"
        class="text-(length:--ui-font-size-xs)/(--ui-font-line-height-reset) text-description tabular-nums"
        aria-live="polite"
        role="status"
      >
        {{ value?.length }}/{{ maxLength }}
      </div>
    </template>
  </B24Input>
</template>

С сочетанием клавиш

Компонент Kbd в слоте #trailing показывает сочетание клавиш Input.

/
<script setup lang="ts">
import CrmSearchIcon from '@bitrix24/b24icons-vue/crm/CrmSearchIcon'

const input = useTemplateRef('input')

defineShortcuts({
  '/': () => {
    input.value?.inputRef?.focus()
  }
})
</script>

<template>
  <B24Input
    ref="input"
    :icon="CrmSearchIcon"
    placeholder="Поиск..."
  >
    <template #trailing>
      <B24Kbd value="/" />
    </template>
  </B24Input>
</template>
<script setup lang="ts">
import { useTemplateRef } from 'vue'
import CrmSearchIcon from '@bitrix24/b24icons-vue/crm/CrmSearchIcon'

const input = useTemplateRef('input')

defineShortcuts({
  '/': () => {
    input.value?.inputRef?.focus()
  }
})
</script>

<template>
  <B24Input
    ref="input"
    :icon="CrmSearchIcon"
    placeholder="Поиск..."
  >
    <template #trailing>
      <B24Kbd value="/" />
    </template>
  </B24Input>
</template>
В этом примере композабл defineShortcuts переводит фокус на Input при нажатии клавиши /.

С маской

Масок во встроенном виде нет, но для маски Input можно использовать библиотеки вроде maska.

<script setup lang="ts">
import { vMaska } from 'maska/vue'
import CreditDebitCardIcon from '@bitrix24/b24icons-vue/main/CreditDebitCardIcon'
import CalendarIcon from '@bitrix24/b24icons-vue/outline/CalendarIcon'
</script>

<template>
  <div class="flex flex-col gap-2">
    <B24Input v-maska="'#### #### #### ####'" placeholder="4242 4242 4242 4242" :icon="CreditDebitCardIcon" />

    <div class="flex items-center gap-2">
      <B24Input v-maska="'##/##'" placeholder="MM/YY" :icon="CalendarIcon" />
      <B24Input v-maska="'###'" placeholder="CVC" />
    </div>
  </div>
</template>

С плавающей подписью

Слот #default позволяет добавить Input плавающую подпись.

<script setup lang="ts">
const value = ref('')
</script>

<template>
  <B24Input id="email" v-model="value" placeholder="" :b24ui="{ base: 'peer' }">
    <label for="email" class="pointer-events-none absolute start-0 -top-[10px] text-label text-(length:--ui-font-size-xs)/(--ui-font-line-height-reset) font-(--ui-font-weight-medium) px-1.5 transition-all peer-focus:-top-[10px] peer-focus:text-label peer-focus:text-(length:--ui-font-size-xs)/(--ui-font-line-height-reset) peer-focus:font-(--ui-font-weight-medium) peer-placeholder-shown:text-(length:--ui-font-size-sm)/(--ui-font-line-height-reset) peer-placeholder-shown:text-legend peer-placeholder-shown:top-[10px] peer-placeholder-shown:font-(--ui-font-weight-normal)">
      <span class="inline-flex bg-(--ui-color-base-white-fixed) px-1">Адрес email</span>
    </label>
  </B24Input>
</template>
<script setup lang="ts">
import { ref } from 'vue'

const value = ref('')
</script>

<template>
  <B24Input id="email" v-model="value" placeholder="" :b24ui="{ base: 'peer' }">
    <label for="email" class="pointer-events-none absolute start-0 -top-[10px] text-label text-(length:--ui-font-size-xs)/(--ui-font-line-height-reset) font-(--ui-font-weight-medium) px-1.5 transition-all peer-focus:-top-[10px] peer-focus:text-label peer-focus:text-(length:--ui-font-size-xs)/(--ui-font-line-height-reset) peer-focus:font-(--ui-font-weight-medium) peer-placeholder-shown:text-(length:--ui-font-size-sm)/(--ui-font-line-height-reset) peer-placeholder-shown:text-legend peer-placeholder-shown:top-[10px] peer-placeholder-shown:font-(--ui-font-weight-normal)">
      <span class="inline-flex bg-(--ui-color-base-white-fixed) px-1">Адрес email</span>
    </label>
  </B24Input>
</template>

Внутри FormField

Input можно использовать внутри компонента FormField, чтобы показывать подпись, справочный текст, признак обязательности и так далее.

Мы не передаём ваш email третьим лицам.
<script setup lang="ts">
import Bitrix24Icon from '@bitrix24/b24icons-vue/common-service/Bitrix24Icon'

const email = ref('')
</script>

<template>
  <B24FormField
    label="Email"
    help="Мы не передаём ваш email третьим лицам."
    required
  >
    <B24Input
      v-model="email"
      placeholder="Введите ваш email"
      :icon="Bitrix24Icon"
    />
  </B24FormField>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import Bitrix24Icon from '@bitrix24/b24icons-vue/common-service/Bitrix24Icon'

const email = ref('')
</script>

<template>
  <B24FormField
    label="Email"
    help="Мы не передаём ваш email третьим лицам."
    required
  >
    <B24Input
      v-model="email"
      placeholder="Введите ваш email"
      :icon="Bitrix24Icon"
    />
  </B24FormField>
</template>
Внутри компонента Form он также обеспечивает валидацию и обработку ошибок.

Внутри FieldGroup

Input можно использовать внутри компонента FieldGroup, чтобы сгруппировать несколько элементов.

https://

<script setup lang="ts">
const value = ref('')
const domains = ['.com', '.dev', '.org']
const domain = ref(domains[0])
</script>

<template>
  <B24FieldGroup>
    <B24Input
      v-model="value"
      placeholder="bitrix24"
      :b24ui="{
        base: 'ps-[48px]',
        leading: 'pointer-events-none'
      }"
    >
      <template #leading>
        <p class="text-(length:--ui-font-size-xs)/(--ui-font-line-height-reset) text-label">
          https://
        </p>
      </template>
    </B24Input>

    <B24SelectMenu
      v-model="domain"
      :items="domains"
      class="w-[85px]"
      :content="{ align: 'end', side: 'bottom', sideOffset: 4 }"
    />
  </B24FieldGroup>
</template>
<script setup lang="ts">
import { ref } from 'vue'

const value = ref('')
const domains = ['.com', '.dev', '.org']
const domain = ref(domains[0])
</script>

<template>
  <B24FieldGroup>
    <B24Input
      v-model="value"
      placeholder="bitrix24"
      :b24ui="{
        base: 'ps-[48px]',
        leading: 'pointer-events-none'
      }"
    >
      <template #leading>
        <p class="text-(length:--ui-font-size-xs)/(--ui-font-line-height-reset) text-label">
          https://
        </p>
      </template>
    </B24Input>

    <B24SelectMenu
      v-model="domain"
      :items="domains"
      class="w-[85px]"
      :content="{ align: 'end', side: 'bottom', sideOffset: 4 }"
    />
  </B24FieldGroup>
</template>

Как поле номера телефона

Input внутри FieldGroup вместе с SelectMenu образует поле номера телефона с выбором кода страны.

+1
<script setup lang="ts">
import { vMaska } from 'maska/vue'
import CrmSearchIcon from '@bitrix24/b24icons-vue/crm/CrmSearchIcon'
import Expand1Icon from '@bitrix24/b24icons-vue/actions/Expand1Icon'

type PhoneCode = {
  name: string
  code: string
  emoji: string
  dialCode: string
  mask: string
}

const phone = ref('')
const countryCode = ref('US')

const { data: phoneCodes, status, execute } = await useLazyFetch<PhoneCode[]>('/api/phone-codes.json', {
  key: 'api-phone-codes',
  immediate: false
})

const country = computed(() => phoneCodes.value?.find(c => c.code === countryCode.value))
const dialCode = computed(() => country.value?.dialCode || '+1')
const mask = computed(() => country.value?.mask || '(###) ###-####')

function onOpen() {
  if (!phoneCodes.value?.length) {
    execute()
  }
}

watch(countryCode, () => {
  phone.value = ''
})
</script>

<template>
  <B24FieldGroup>
    <B24SelectMenu
      v-model="countryCode"
      :items="phoneCodes"
      value-key="code"
      :search-input="{
        placeholder: 'Найдите страну...',
        icon: CrmSearchIcon,
        loading: status === 'pending'
      }"
      :filter-fields="['name', 'code', 'dialCode']"
      :content="{ align: 'start' }"
      class="w-[62px]"
      :b24ui="{
        base: 'pe-8',
        content: 'min-w-fit',
        viewport: 'min-w-fit',
        item: 'min-w-fit',
        placeholder: 'hidden',
        trailingIcon: 'size-4'
      }"
      :trailing-icon="Expand1Icon"
      @update:open="onOpen"
    >
      <span class="size-5 flex items-center text-lg">
        {{ country?.emoji || '\u{1F1FA}\u{1F1F8}' }}
      </span>

      <template #item-leading="{ item }">
        <span class="size-5 flex items-center text-lg">
          {{ item.emoji }}
        </span>
      </template>

      <template #item-label="{ item }">
        {{ item.name }} ({{ item.dialCode }})
      </template>
    </B24SelectMenu>

    <B24Input
      v-model="phone"
      v-maska="mask"
      :placeholder="mask.replaceAll('#', '_')"
      :style="{ '--dial-code-length': `${dialCode.length + 1.5}ch` }"
      class="w-full max-w-[200px]"
      :b24ui="{
        base: 'ps-(--dial-code-length)',
        leading: 'pointer-events-none text-label'
      }"
    >
      <template #leading>
        {{ dialCode }}
      </template>
    </B24Input>
  </B24FieldGroup>
</template>
<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { vMaska } from 'maska/vue'
import CrmSearchIcon from '@bitrix24/b24icons-vue/crm/CrmSearchIcon'
import Expand1Icon from '@bitrix24/b24icons-vue/actions/Expand1Icon'

type PhoneCode = {
  name: string
  code: string
  emoji: string
  dialCode: string
  mask: string
}

const phone = ref('')
const countryCode = ref('US')

const { data: phoneCodes, status, execute } = await useLazyFetch<PhoneCode[]>('/api/phone-codes.json', {
  key: 'api-phone-codes',
  immediate: false
})

const country = computed(() => phoneCodes.value?.find(c => c.code === countryCode.value))
const dialCode = computed(() => country.value?.dialCode || '+1')
const mask = computed(() => country.value?.mask || '(###) ###-####')

function onOpen() {
  if (!phoneCodes.value?.length) {
    execute()
  }
}

watch(countryCode, () => {
  phone.value = ''
})
</script>

<template>
  <B24FieldGroup>
    <B24SelectMenu
      v-model="countryCode"
      :items="phoneCodes"
      value-key="code"
      :search-input="{
        placeholder: 'Найдите страну...',
        icon: CrmSearchIcon,
        loading: status === 'pending'
      }"
      :filter-fields="['name', 'code', 'dialCode']"
      :content="{ align: 'start' }"
      class="w-[62px]"
      :b24ui="{
        base: 'pe-8',
        content: 'min-w-fit',
        viewport: 'min-w-fit',
        item: 'min-w-fit',
        placeholder: 'hidden',
        trailingIcon: 'size-4'
      }"
      :trailing-icon="Expand1Icon"
      @update:open="onOpen"
    >
      <span class="size-5 flex items-center text-lg">
        {{ country?.emoji || '\u{1F1FA}\u{1F1F8}' }}
      </span>

      <template #item-leading="{ item }">
        <span class="size-5 flex items-center text-lg">
          {{ item.emoji }}
        </span>
      </template>

      <template #item-label="{ item }">
        {{ item.name }} ({{ item.dialCode }})
      </template>
    </B24SelectMenu>

    <B24Input
      v-model="phone"
      v-maska="mask"
      :placeholder="mask.replaceAll('#', '_')"
      :style="{ '--dial-code-length': `${dialCode.length + 1.5}ch` }"
      class="w-full max-w-[200px]"
      :b24ui="{
        base: 'ps-(--dial-code-length)',
        leading: 'pointer-events-none text-label'
      }"
    >
      <template #leading>
        {{ dialCode }}
      </template>
    </B24Input>
  </B24FieldGroup>
</template>

API

Пропсы

Prop Default Type
as'div'any

The element or component this component should render as.

id string
name string
type'text' "number" | "image" | "text" | "button" | "search" | "time" | "color" | "checkbox" | "date" | "datetime-local" | "email" | "file" | "hidden" | "month" | "password" | "radio" | "range" | "reset" | "submit" | "tel" | "url" | "week" | string & {}
placeholder string

The placeholder text when the input is empty.

color'air-primary'"air-primary" | "air-primary-success" | "air-primary-alert" | "air-primary-warning" | "air-primary-copilot"
size'md' "xss" | "xs" | "sm" | "md" | "lg" | "xl"
noPaddingfalseboolean

Removes padding from input

noBorderfalseboolean

Removes all borders (rings)

underlinefalseboolean

Removes all borders (rings) except the bottom one

roundedfalseboolean

Rounds the corners of the input

requiredfalseboolean
autocomplete'off' string & {} | "on" | "off"
autofocusfalseboolean
autofocusDelay0 number
disabledfalseboolean
tag string
tagColor'air-primary'"air-primary" | "air-primary-success" | "air-primary-alert" | "air-primary-warning" | "air-primary-copilot" | "air-secondary" | "air-secondary-alert" | "air-secondary-accent" | "air-secondary-accent-1" | "air-secondary-accent-2" | "air-tertiary" | "air-selection"
highlightboolean

Highlight the ring color like a focus state.

fixedboolean

Keep the mobile text size on all breakpoints. (Left for backward compatibility.)

modelValue _Number<_Optional<_Nullable<T, Mod>, Mod>, Mod>
defaultValue _Number<_Optional<_Nullable<T, Mod>, Mod>, Mod>
modelModifiers Mod
iconIconComponent

Display an icon on the left side.

avatar AvatarProps

Display an avatar on the left side.

loadingboolean

When true, the loading icon will be displayed.

trailingboolean

When true, the icon will be displayed on the right side.

trailingIconIconComponent

Display an icon on the right side.

list string
max string | number
maxlength string | number
min string | number
minlength string | number
pattern string
readonly false | true | "true" | "false"
step string | number
b24ui { root?: SlotClass; base?: SlotClass; leading?: SlotClass; leadingIcon?: SlotClass; leadingAvatar?: SlotClass; leadingAvatarSize?: SlotClass; trailing?: SlotClass; trailingIcon?: SlotClass; tag?: SlotClass; }
Компонент поддерживает и все нативные HTML-атрибуты <input>.

Слоты

Slot Type
leading{ b24ui: object; }
default{ b24ui: object; }
trailing{ b24ui: object; }

События

Event Type
update:modelValue[value: _Number<_Optional<_Nullable<T, Mod>, Mod>, Mod>]
blur[event: FocusEvent]
change[event: Event]

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

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

ИмяТип
inputRefRef<HTMLInputElement | null>

Тема

https://github.com/bx-shef/b24-ui/tree/main/src/theme/input.ts
export default {
  slots: {
    root: 'isolate relative inline-flex items-center',
    base: 'px-3 w-full py-0 border-0 focus:outline-none disabled:cursor-not-allowed disabled:pointer-events-auto disabled:select-none disabled:opacity-30 disabled:resize-none appearance-none transition-colors duration-300 ease-linear text-(--ui-color-base-1) style-blurred-bg-input placeholder:text-(--ui-color-design-plain-na-content-secondary) hover:text-(--ui-color-base-1) focus:text-(--ui-color-base-1) active:text-(--ui-color-base-1) font-[family-name:var(--ui-font-family-primary)] font-(--ui-font-weight-regular) align-middle text-ellipsis whitespace-nowrap',
    leading: 'absolute inset-y-0 start-0 flex items-center',
    leadingIcon: 'shrink-0 text-(--b24ui-icon-color)',
    leadingAvatar: 'shrink-0',
    leadingAvatarSize: '',
    trailing: 'absolute inset-y-0 end-0 flex items-center',
    trailingIcon: 'shrink-0 text-(--b24ui-icon-color)',
    tag: 'pointer-events-none select-none absolute z-10 -top-[7px] right-[14px] flex flex-col justify-center items-center'
  },
  variants: {
    fieldGroup: {
      horizontal: {
        root: 'group leading-none has-focus-visible:z-[1]',
        base: 'focus-visible:outline-none ring ring-inset ring-1 focus-visible:ring-2 group-not-only:group-first:rounded-e-3xl group-not-only:group-last:rounded-s-none group-not-last:group-not-first:rounded-none group-not-only:group-first:rounded-e-none group-not-only:group-last:rounded-s-none group-not-last:group-not-first:rounded-none group-not-only:group-first:border-e-0 group-not-only:group-not-first:border-s-0'
      },
      vertical: {
        root: 'group has-focus-visible:z-[1]',
        base: 'focus-visible:outline-none ring ring-inset ring-1 focus-visible:ring-2 group-not-only:group-first:rounded-b-none group-not-only:group-last:rounded-t-none group-not-last:group-not-first:rounded-none'
      }
    },
    noSplit: {
      false: "group-not-only:not-first:after:content-[''] group-not-only:not-first:after:absolute group-not-only:not-first:after:top-[7px] group-not-only:not-first:after:bottom-[6px] group-not-only:not-first:after:left-0 group-not-only:not-first:after:w-px group-not-only:not-first:after:bg-current/30"
    },
    size: {
      xss: {
        base: 'h-[20px] gap-1 text-(length:--ui-font-size-4xs)/[normal]',
        leading: 'px-1',
        trailing: 'px-1',
        leadingIcon: 'size-[12px]',
        leadingAvatarSize: '3xs',
        trailingIcon: 'size-[12px]'
      },
      xs: {
        base: 'h-[24px] gap-1 text-(length:--ui-font-size-xs)/[normal]',
        leading: 'px-1',
        trailing: 'px-1',
        leadingIcon: 'size-[14px]',
        leadingAvatarSize: '3xs',
        trailingIcon: 'size-[14px]'
      },
      sm: {
        base: 'h-[28px] gap-1.5 text-(length:--ui-font-size-sm)/[normal]',
        leading: 'px-1.5',
        trailing: 'px-1.5',
        leadingIcon: 'size-[16px]',
        leadingAvatar: 'size-[16px]',
        leadingAvatarSize: '2xs',
        trailingIcon: 'size-[16px]'
      },
      md: {
        base: 'h-[34px] gap-1.5 text-(length:--ui-font-size-lg)/[normal]',
        leading: 'px-2',
        trailing: 'px-2',
        leadingIcon: 'size-4.5',
        leadingAvatarSize: '2xs',
        trailingIcon: 'size-4.5'
      },
      lg: {
        base: 'h-[38px] gap-2 text-(length:--ui-font-size-lg)/[normal]',
        leading: 'px-2',
        trailing: 'px-2',
        leadingIcon: 'size-[22px]',
        leadingAvatarSize: '2xs',
        trailingIcon: 'size-[22px]'
      },
      xl: {
        base: 'h-[46px] gap-2 text-(length:--ui-font-size-2xl)/[normal]',
        leading: 'px-2',
        trailing: 'px-2',
        leadingIcon: 'size-[22px]',
        leadingAvatarSize: '2xs',
        trailingIcon: 'size-[22px]'
      }
    },
    color: {
      'air-primary': {
        base: 'style-filled'
      },
      'air-primary-success': {
        base: 'style-filled-success'
      },
      'air-primary-alert': {
        base: 'style-filled-alert'
      },
      'air-primary-copilot': {
        base: 'style-filled-copilot'
      },
      'air-primary-warning': {
        base: 'style-filled-warning'
      },
      default: {
        base: 'style-old-default'
      },
      danger: {
        base: 'style-old-danger'
      },
      success: {
        base: 'style-old-success'
      },
      warning: {
        base: 'style-old-warning'
      },
      primary: {
        base: 'style-old-primary'
      },
      secondary: {
        base: 'style-old-secondary'
      },
      collab: {
        base: 'style-old-collab'
      },
      ai: {
        base: 'style-old-ai'
      }
    },
    rounded: {
      true: 'rounded-(--ui-border-radius-3xl)',
      false: 'rounded-(--ui-border-radius-sm)'
    },
    noPadding: {
      true: {
        base: 'px-0'
      }
    },
    noBorder: {
      true: 'ring-0 focus-visible:ring-0 style-transparent-bg'
    },
    underline: {
      true: 'rounded-none ring-0 focus-visible:ring-0 style-transparent-bg border-b-1 border-b-(--ui-color-design-outline-stroke)'
    },
    leading: {
      true: ''
    },
    trailing: {
      true: ''
    },
    loading: {
      true: ''
    },
    highlight: {
      true: 'ring ring-inset ring-(--b24ui-border-color)'
    },
    fixed: {
      false: ''
    },
    type: {
      file: 'file:me-1.5 file:text-(--ui-color-design-plain-na-content-secondary) file:outline-none'
    }
  },
  compoundVariants: [
    {
      highlight: false,
      noBorder: false,
      underline: false,
      class: {
        base: 'ring ring-inset ring-(--ui-color-design-outline-stroke) focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-(--b24ui-border-color) hover:not-disabled:not-data-disabled:ring-1 hover:not-disabled:not-data-disabled:ring-inset hover:not-disabled:not-data-disabled:ring-(--b24ui-border-color) data-[state=open]:ring-1 data-[state=open]:ring-inset data-[state=open]:ring-(--b24ui-border-color)'
      }
    },
    {
      highlight: true,
      noBorder: false,
      underline: false,
      class: {
        base: 'ring ring-inset ring-(--b24ui-border-color) focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-(--b24ui-border-color) hover:ring-1 hover:ring-inset hover:ring-(--b24ui-border-color) data-[state=open]:ring-1 data-[state=open]:ring-inset data-[state=open]:ring-(--b24ui-border-color)'
      }
    },
    {
      noBorder: false,
      underline: true,
      class: {
        base: 'focus-visible:border-(--b24ui-border-color) hover:not-disabled:not-data-disabled:border-(--b24ui-border-color) data-[state=open]:border-(--b24ui-border-color)'
      }
    },
    {
      highlight: true,
      noBorder: false,
      underline: true,
      class: {
        base: 'ring-0 border-b-(--b24ui-border-color)'
      }
    },
    {
      highlight: true,
      noBorder: true,
      underline: false,
      class: {
        base: 'ring-0'
      }
    },
    {
      type: 'file',
      size: 'xss',
      class: 'py-[2px]'
    },
    {
      type: 'file',
      size: 'xs',
      class: 'py-[4px]'
    },
    {
      type: 'file',
      size: 'sm',
      class: 'py-[5px]'
    },
    {
      type: 'file',
      size: 'md',
      class: 'py-[7px]'
    },
    {
      type: 'file',
      size: 'lg',
      class: 'py-[9px]'
    },
    {
      type: 'file',
      size: 'xl',
      class: 'py-[11px]'
    },
    {
      leading: true,
      noPadding: false,
      size: 'xss',
      class: 'ps-[20px]'
    },
    {
      leading: true,
      noPadding: false,
      size: 'xs',
      class: 'ps-[22px]'
    },
    {
      leading: true,
      noPadding: false,
      size: 'sm',
      class: 'ps-[28px]'
    },
    {
      leading: true,
      noPadding: false,
      size: 'md',
      class: 'ps-[32px]'
    },
    {
      leading: true,
      noPadding: false,
      size: 'lg',
      class: 'ps-[32px]'
    },
    {
      leading: true,
      noPadding: false,
      size: 'xl',
      class: 'ps-[32px]'
    },
    {
      trailing: true,
      noPadding: false,
      size: 'xss',
      class: 'pe-[20px]'
    },
    {
      trailing: true,
      noPadding: false,
      size: 'xs',
      class: 'pe-[22px]'
    },
    {
      trailing: true,
      noPadding: false,
      size: 'sm',
      class: 'pe-[28px]'
    },
    {
      trailing: true,
      noPadding: false,
      size: 'md',
      class: 'pe-[34px]'
    },
    {
      trailing: true,
      noPadding: false,
      size: 'lg',
      class: 'pe-[38px]'
    },
    {
      trailing: true,
      noPadding: false,
      size: 'xl',
      class: 'pe-[38px]'
    },
    {
      loading: true,
      leading: true,
      class: {
        leadingIcon: 'size-[21px]'
      }
    },
    {
      loading: true,
      leading: false,
      trailing: true,
      class: {
        trailingIcon: 'size-[21px]'
      }
    },
    {
      loading: true,
      leading: true,
      noPadding: true,
      class: {
        base: 'ps-[34px]'
      }
    },
    {
      loading: true,
      leading: false,
      trailing: true,
      noPadding: true,
      class: {
        base: 'pe-[34px]'
      }
    },
    {
      fieldGroup: [
        'horizontal',
        'vertical'
      ],
      size: [
        'xl',
        'lg',
        'md'
      ],
      rounded: false,
      class: 'rounded-(--ui-border-radius-md)'
    },
    {
      fieldGroup: [
        'horizontal',
        'vertical'
      ],
      size: 'sm',
      rounded: false,
      class: 'rounded-(--ui-border-radius-sm)'
    },
    {
      fieldGroup: [
        'horizontal',
        'vertical'
      ],
      size: 'xs',
      rounded: false,
      class: 'rounded-(--ui-border-radius-xs)'
    },
    {
      fieldGroup: [
        'horizontal',
        'vertical'
      ],
      size: 'xss',
      rounded: false,
      class: 'rounded-[5px]'
    },
    {
      fixed: false,
      size: 'xss',
      class: 'md:text-(length:--ui-font-size-4xs)/[normal]'
    },
    {
      fixed: false,
      size: 'xs',
      class: 'md:text-(length:--ui-font-size-xs)/[normal]'
    },
    {
      fixed: false,
      size: 'sm',
      class: 'md:text-(length:--ui-font-size-sm)/[normal]'
    },
    {
      fixed: false,
      size: 'md',
      class: 'md:text-(length:--ui-font-size-lg)/[normal]'
    },
    {
      fixed: false,
      size: 'lg',
      class: 'md:text-(length:--ui-font-size-lg)/[normal]'
    }
  ],
  defaultVariants: {
    color: 'air-primary',
    size: 'md'
  }
}