Кнопка
Кнопка; поддерживаются разные типы, размеры, состояния и фирменные цвета (китайский стиль, 国风 (гофэн — национальный колорит)).
Базовое использование
<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><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>Различные размеры
<script setup lang="ts">
</script>
<template>
<LhButton size="large">Большая кнопка</LhButton>
<LhButton>Обычная кнопка</LhButton>
<LhButton size="small">Маленькая кнопка</LhButton>
<LhButton size="mini">Мини-кнопка</LhButton>
</template><script>
export default {}
</script>
<template>
<LhButton size="large">Большая кнопка</LhButton>
<LhButton>Обычная кнопка</LhButton>
<LhButton size="small">Маленькая кнопка</LhButton>
<LhButton size="mini">Мини-кнопка</LhButton>
</template>Простая кнопка
<script setup lang="ts">
</script>
<template>
<LhButton plain>Простая кнопка</LhButton>
<LhButton type="primary" plain>Основная</LhButton>
<LhButton type="success" plain>Успех</LhButton>
</template><script>
export default {}
</script>
<template>
<LhButton plain>Простая кнопка</LhButton>
<LhButton type="primary" plain>Основная</LhButton>
<LhButton type="success" plain>Успех</LhButton>
</template>Круглая кнопка
<script setup lang="ts">
</script>
<template>
<LhButton circle>Кр</LhButton>
<LhButton type="primary" circle>Ос</LhButton>
<LhButton type="success" circle>Ус</LhButton>
</template><script>
export default {}
</script>
<template>
<LhButton circle>Кр</LhButton>
<LhButton type="primary" circle>Ос</LhButton>
<LhButton type="success" circle>Ус</LhButton>
</template>Состояние загрузки
<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><script>
export default {
data() {
return { loading1: false }
},
}
</script>
<template>
<!-- Загрузить по клику -->
<LhButton :loading="loading1" @click="loading1 = true">Загрузить по клику</LhButton>
<!-- Загрузка -->
<LhButton type="primary" loading>Загрузка</LhButton>
</template>Недоступное состояние
<script setup lang="ts">
</script>
<template>
<LhButton disabled>Отключённая кнопка</LhButton>
<LhButton type="primary" disabled>Основная</LhButton>
</template><script>
export default {}
</script>
<template>
<LhButton disabled>Отключённая кнопка</LhButton>
<LhButton type="primary" disabled>Основная</LhButton>
</template>Block-кнопка
<script setup lang="ts">
</script>
<template>
<!-- Блочная кнопка -->
<LhButton block>Блочная кнопка</LhButton>
<!-- Основная блочная -->
<LhButton type="primary" block>Основная блочная</LhButton>
</template><script>
export default {}
</script>
<template>
<!-- Блочная кнопка -->
<LhButton block>Блочная кнопка</LhButton>
<!-- Основная блочная -->
<LhButton type="primary" block>Основная блочная</LhButton>
</template>Кнопка с скруглением
round придаёт форме сильно скруглённый капсульный вид (в отличие от полностью круглого circle).
<script setup lang="ts">
</script>
<template>
<LhButton round>Скруглённая кнопка</LhButton>
<LhButton type="primary" round>Основная скруглённая</LhButton>
</template><script>
export default {}
</script>
<template>
<LhButton round>Скруглённая кнопка</LhButton>
<LhButton type="primary" round>Основная скруглённая</LhButton>
</template>Кнопка с иконкой
icon принимает имя иконки; также доступен слот #icon для пользовательского рендеринга.
<script setup lang="ts">
</script>
<template>
<!-- Поиск -->
<LhButton icon="search">Поиск</LhButton>
<!-- Избранное -->
<LhButton type="primary" icon="star">Избранное</LhButton>
<!-- Слот пользовательской иконки -->
<LhButton circle>
<template #icon>🔍</template>
</LhButton>
</template><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.
<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><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.
<script setup lang="ts">
</script>
<template>
<LhButton type="primary" :sx="{ mt: 2, mx: 1 }">Отступ сверху 2, по горизонтали 1</LhButton>
</template><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-переменные.
<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><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 с языковыми пакетами.
<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><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 | Состояние загрузки | boolean | false |
| disabled | Недоступное состояние | boolean | false |
| plain | Простая кнопка | boolean | false |
| block | Блочная кнопка | boolean | false |
| round | Кнопка с скруглением | boolean | false |
| circle | Круглая кнопка | boolean | false |
| 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 | Фоновый узор на уровне компонента; переопределяет настройки ConfigProvider | string | — |
| sx | Сокращённые свойства компоновки sx | LhSxProps | — |
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
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
export type LhButtonType = (typeof LH_BUTTON_TYPE_CONST)[keyof typeof LH_BUTTON_TYPE_CONST]LhButtonSize
export type LhButtonSize = (typeof LH_BUTTON_SIZE_CONST)[keyof typeof LH_BUTTON_SIZE_CONST]LhIconName (из @lh-ui/share/core/icon (svgs.ts))
export type LhIconName = keyof typeof LH_ICON_SVGS_CONST