Skip to content
API 风格:

Кнопка ​

Кнопка; поддерживаются разные типы, размеры, состояния и фирменные цвета (китайский стиль, 国风 (гофэн — национальный колорит)).

Базовое использование ​

Базовое использование
vue
<script setup lang="ts">
</script>

<template>
  <!-- Обычная -->
  <LhButton>Обычная кнопка</LhButton>
  <!-- primary -->
  <LhButton type="primary">Основная</LhButton>
  <!-- success -->
  <LhButton type="success">Успех</LhButton>
  <!-- warning -->
  <LhButton type="warning">Предупреждение</LhButton>
  <!-- danger -->
  <LhButton type="danger">Опасность</LhButton>
  <!-- info -->
  <LhButton type="info">Информация</LhButton>
</template>
vue
<script>
export default {}
</script>

<template>
  <!-- Обычная -->
  <LhButton>Обычная кнопка</LhButton>
  <!-- primary -->
  <LhButton type="primary">Основная</LhButton>
  <!-- success -->
  <LhButton type="success">Успех</LhButton>
  <!-- warning -->
  <LhButton type="warning">Предупреждение</LhButton>
  <!-- danger -->
  <LhButton type="danger">Опасность</LhButton>
  <!-- info -->
  <LhButton type="info">Информация</LhButton>
</template>

Различные размеры ​

Различные размеры
vue
<script setup lang="ts">
</script>

<template>
  <LhButton size="large">Большая кнопка</LhButton>
  <LhButton>Обычная кнопка</LhButton>
  <LhButton size="small">Маленькая кнопка</LhButton>
  <LhButton size="mini">Мини-кнопка</LhButton>
</template>
vue
<script>
export default {}
</script>

<template>
  <LhButton size="large">Большая кнопка</LhButton>
  <LhButton>Обычная кнопка</LhButton>
  <LhButton size="small">Маленькая кнопка</LhButton>
  <LhButton size="mini">Мини-кнопка</LhButton>
</template>

Простая кнопка ​

Простая кнопка
vue
<script setup lang="ts">
</script>

<template>
  <LhButton plain>Простая кнопка</LhButton>
  <LhButton type="primary" plain>Основная</LhButton>
  <LhButton type="success" plain>Успех</LhButton>
</template>
vue
<script>
export default {}
</script>

<template>
  <LhButton plain>Простая кнопка</LhButton>
  <LhButton type="primary" plain>Основная</LhButton>
  <LhButton type="success" plain>Успех</LhButton>
</template>

Круглая кнопка ​

Круглая кнопка
vue
<script setup lang="ts">
</script>

<template>
  <LhButton circle>Кр</LhButton>
  <LhButton type="primary" circle>Ос</LhButton>
  <LhButton type="success" circle>Ус</LhButton>
</template>
vue
<script>
export default {}
</script>

<template>
  <LhButton circle>Кр</LhButton>
  <LhButton type="primary" circle>Ос</LhButton>
  <LhButton type="success" circle>Ус</LhButton>
</template>

Состояние загрузки ​

Состояние загрузки
vue
<script setup lang="ts">
import { ref } from 'vue'

const loading1 = ref(false)
</script>

<template>
  <!-- Загрузить по клику -->
  <LhButton :loading="loading1" @click="loading1 = true">Загрузить по клику</LhButton>
  <!-- Загрузка -->
  <LhButton type="primary" loading>Загрузка</LhButton>
</template>
vue
<script>
export default {
  data() {
    return { loading1: false }
  },
}
</script>

<template>
  <!-- Загрузить по клику -->
  <LhButton :loading="loading1" @click="loading1 = true">Загрузить по клику</LhButton>
  <!-- Загрузка -->
  <LhButton type="primary" loading>Загрузка</LhButton>
</template>

Недоступное состояние ​

Недоступное состояние
vue
<script setup lang="ts">
</script>

<template>
  <LhButton disabled>Отключённая кнопка</LhButton>
  <LhButton type="primary" disabled>Основная</LhButton>
</template>
vue
<script>
export default {}
</script>

<template>
  <LhButton disabled>Отключённая кнопка</LhButton>
  <LhButton type="primary" disabled>Основная</LhButton>
</template>

Block-кнопка ​

Block-кнопка
vue
<script setup lang="ts">
</script>

<template>
  <!-- Блочная кнопка -->
  <LhButton block>Блочная кнопка</LhButton>
  <!-- Основная блочная -->
  <LhButton type="primary" block>Основная блочная</LhButton>
</template>
vue
<script>
export default {}
</script>

<template>
  <!-- Блочная кнопка -->
  <LhButton block>Блочная кнопка</LhButton>
  <!-- Основная блочная -->
  <LhButton type="primary" block>Основная блочная</LhButton>
</template>

Кнопка с скруглением ​

round придаёт форме сильно скруглённый капсульный вид (в отличие от полностью круглого circle).

Кнопка с скруглением
vue
<script setup lang="ts">
</script>

<template>
  <LhButton round>Скруглённая кнопка</LhButton>
  <LhButton type="primary" round>Основная скруглённая</LhButton>
</template>
vue
<script>
export default {}
</script>

<template>
  <LhButton round>Скруглённая кнопка</LhButton>
  <LhButton type="primary" round>Основная скруглённая</LhButton>
</template>

Кнопка с иконкой ​

icon принимает имя иконки; также доступен слот #icon для пользовательского рендеринга.

Кнопка с иконкой
vue
<script setup lang="ts">
</script>

<template>
  <!-- Поиск -->
  <LhButton icon="search">Поиск</LhButton>
  <!-- Избранное -->
  <LhButton type="primary" icon="star">Избранное</LhButton>
  <!-- Слот пользовательской иконки -->
  <LhButton circle>
    <template #icon>🔍</template>
  </LhButton>
</template>
vue
<script>
export default {}
</script>

<template>
  <!-- Поиск -->
  <LhButton icon="search">Поиск</LhButton>
  <!-- Избранное -->
  <LhButton type="primary" icon="star">Избранное</LhButton>
  <!-- Слот пользовательской иконки -->
  <LhButton circle>
    <template #icon>🔍</template>
  </LhButton>
</template>

Кнопка-ссылка ​

После задания href рендерится тег <a>, а target управляет способом открытия; если href не задан, native-type определяет нативный тип button.

Кнопка-ссылка
GitHub
vue
<script setup lang="ts">
</script>

<template>
  <LhButton href="https://github.com/lhgb-top/lh-ui-plus" target="_blank">GitHub</LhButton>
  <LhButton native-type="submit" type="primary">Отправить</LhButton>
</template>
vue
<script>
export default {}
</script>

<template>
  <LhButton href="https://github.com/lhgb-top/lh-ui-plus" target="_blank">GitHub</LhButton>
  <LhButton native-type="submit" type="primary">Отправить</LhButton>
</template>

Быстрая компоновка sx ​

Через свойство sx можно быстро задать отступы и размеры, не пишу дополнительный CSS.

Отступы через sx
vue
<script setup lang="ts">
</script>

<template>
  <LhButton type="primary" :sx="{ mt: 2, mx: 1 }">Отступ сверху 2, по горизонтали 1</LhButton>
</template>
vue
<script>
export default {}
</script>

<template>
  <LhButton type="primary" :sx="{ mt: 2, mx: 1 }">Отступ сверху 2, по горизонтали 1</LhButton>
</template>

sx основан на шаге 8px: mt: 2 → marginTop: 16px, mx: 1 → marginLeft: 8px; marginRight: 8px. Полный список свойств — в разделе Быстрая раскладка sx.

Пользовательская тема ​

Применение к кнопкам собственных фирменных цветов через свойство themeVars компонента LhConfigProvider, переопределяющее CSS-переменные.

Тема 青花瓷 (сине-белый фарфор)
vue
<script setup lang="ts">
import { LhConfigProvider, LhButton } from '@lh-ui/vue3'

const cerblueTheme = {
  'primary-color': '#2B4C7C',
  'primary-color-hover': '#3D649E',
  'primary-color-bg': '#E8EDF3',
  'bg-color': '#F0F4F8',
}
</script>

<template>
  <LhConfigProvider :theme-vars="cerblueTheme">
    <!-- Фарфоровая кнопка -->
    <LhButton type="primary">Фарфоровая кнопка</LhButton>
    <!-- Успех -->
    <LhButton type="success">Успех</LhButton>
  </LhConfigProvider>
</template>
vue
<script>
import { LhConfigProvider, LhButton } from '@lh-ui/vue3'

export default {
  components: { LhConfigProvider, LhButton },
  data() {
    return {
      cerblueTheme: {
        'primary-color': '#2B4C7C',
        'primary-color-hover': '#3D649E',
        'primary-color-bg': '#E8EDF3',
        'bg-color': '#F0F4F8',
      },
    }
  },
}
</script>

<template>
  <LhConfigProvider :theme-vars="cerblueTheme">
    <!-- Фарфоровая кнопка -->
    <LhButton type="primary">Фарфоровая кнопка</LhButton>
    <!-- Успех -->
    <LhButton type="success">Успех</LhButton>
  </LhConfigProvider>
</template>

Остальные темы — в разделе Кастомизация темы.

Интернационализация ​

Текст кнопки можно интернационализировать через LhConfigProvider с языковыми пакетами.

Интернационализация
vue
<script setup lang="ts">
import { ref, computed } from 'vue'
import { LhConfigProvider, LhButton, zhCN, enUS } from '@lh-ui/vue3'

const locale = ref('zh-CN')
const messages = computed(() => locale.value === 'zh-CN' ? zhCN : enUS)
</script>

<template>
  <LhConfigProvider :locale="messages">
    <LhButton @click="locale = locale === 'zh-CN' ? 'en-US' : 'zh-CN'">
      {{ locale === 'zh-CN' ? '切换至英文' : 'Switch to Chinese' }}
    </LhButton>
  </LhConfigProvider>
</template>
vue
<script>
import { LhConfigProvider, LhButton, zhCN, enUS } from '@lh-ui/vue3'

export default {
  components: { LhConfigProvider, LhButton },
  data() {
    return { locale: 'zh-CN' }
  },
  computed: {
    messages() {
      return this.locale === 'zh-CN' ? zhCN : enUS
    },
  },
}
</script>

<template>
  <LhConfigProvider :locale="messages">
    <LhButton @click="locale = locale === 'zh-CN' ? 'en-US' : 'zh-CN'">
      {{ locale === 'zh-CN' ? '切换至英文' : 'Switch to Chinese' }}
    </LhButton>
  </LhConfigProvider>
</template>

Button API ​

Props ​

СвойствоОписаниеТипПо умолчанию
typeТип кнопки"success" | "warning" | "error" | "info" | "danger" | "default" | "primary"LH_BUTTON_TYPE_CONST.default
sizeРазмер кнопки; если не передан, наследуется от ConfigProvider"small" | "medium" | "large" | "mini" | "x-large"—
loadingСостояние загрузкиbooleanfalse
disabledНедоступное состояниеbooleanfalse
plainПростая кнопкаbooleanfalse
blockБлочная кнопкаbooleanfalse
roundКнопка с скруглениемbooleanfalse
circleКруглая кнопкаbooleanfalse
iconИмя иконки (встроенная иконка LhIcon, например search; для пользовательского рендеринга переопределите слотом icon)LhIconName—
nativeTypeНативный тип button (действует только если не передан href)"button" | "submit" | "reset"'button'
hrefАдрес ссылки (если передан, рендерится <a> вместо <button>)string''
targetСпособ открытия ссылкиstring'_self'
themeVarsПеременные темы на уровне компонента; переопределяют настройки ConfigProvider{ [x: string]: string; }—
bgPatternФоновый узор на уровне компонента; переопределяет настройки ConfigProviderstring—
sxСокращённые свойства компоновки sxLhSxProps—

Events ​

СобытиеОписаниеПараметр обратного вызова
clickСобытие клика(event: MouseEvent)

Slots ​

СлотОписание
defaultСодержимое кнопки
iconПользовательский рендеринг иконки (переопределяет умолчательный LhIcon свойства icon)

Доступность ​

  • Кольцо фокуса клавиатуры: корневой элемент единообразно предоставляет кольцо фокуса на :focus-visible (показывается при навигации с клавиатуры, не показывается при клике мышью), окрашивается через тематическую переменную --lh-primary-color и автоматически следует светлому/тёмному режиму — дополнительная настройка не требуется
  • Имя кнопки с иконкой: если у кнопки есть только иконка без текста (например, круглая кнопка-иконка), скринридер не сможет узнать её назначение — необходимо передать aria-label, это свойство автоматически пробрасывается на корневой элемент. В icon напрямую передаётся имя встроенной иконки (например icon="search"); для рендеринга, выходящего за рамки иконок, используйте слот icon:
    vue
    <LhButton circle aria-label="Поиск">
      <template #icon>
        <LhIcon name="search" />
      </template>
    </LhButton>
  • Снижение анимации: индикатор загрузки уважает системную настройку prefers-reduced-motion (при «уменьшить эффекты движения» вращение отключается)

Типы ​

TypeScript-типы, экспортируемые этим компонентом (извлечены автоматически из packages/components/button/src/types.ts и исходников @lh-ui/share/core/*; раскройте нужный пункт, чтобы увидеть полное определение; описания свойств — в таблице Props выше):

LhButtonProps
ts
export interface LhButtonProps {
  type?: LhButtonType
  /** Размер; необязателен. Если не передан, наследуется от ConfigProvider */
  size?: LhButtonSize
  loading?: boolean
  disabled?: boolean
  plain?: boolean
  block?: boolean
  round?: boolean
  circle?: boolean
  /** Имя иконки (встроенная иконка LhIcon, например `search`; для пользовательского рендеринга переопределите слотом `icon`) */
  icon?: LhIconName
  nativeType?: 'button' | 'submit' | 'reset'
  href?: string
  target?: string
  /** Переменные темы на уровне компонента; переопределяют глобальные themeVars и componentTheme из ConfigProvider */
  themeVars?: Record<string, string>
  /** Фоновый узор на уровне компонента; переопределяет настройки ConfigProvider (не подчиняется белому списку patternComponents) */
  bgPattern?: string
  /** Сокращённые свойства компоновки sx */
  sx?: LhSxProps
}
LhButtonType
ts
export type LhButtonType = (typeof LH_BUTTON_TYPE_CONST)[keyof typeof LH_BUTTON_TYPE_CONST]
LhButtonSize
ts
export type LhButtonSize = (typeof LH_BUTTON_SIZE_CONST)[keyof typeof LH_BUTTON_SIZE_CONST]
LhIconName (из @lh-ui/share/core/icon (svgs.ts))
ts
export type LhIconName = keyof typeof LH_ICON_SVGS_CONST

Красота традиций — основа кода