checkbox-button.vue 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <template>
  2. <label :class="labelKls">
  3. <input
  4. v-if="trueLabel || falseLabel"
  5. v-model="model"
  6. :class="ns.be('button', 'original')"
  7. type="checkbox"
  8. :name="name"
  9. :tabindex="tabindex"
  10. :disabled="isDisabled"
  11. :true-value="trueLabel"
  12. :false-value="falseLabel"
  13. @change="handleChange"
  14. @focus="isFocused = true"
  15. @blur="isFocused = false"
  16. />
  17. <input
  18. v-else
  19. v-model="model"
  20. :class="ns.be('button', 'original')"
  21. type="checkbox"
  22. :name="name"
  23. :tabindex="tabindex"
  24. :disabled="isDisabled"
  25. :value="label"
  26. @change="handleChange"
  27. @focus="isFocused = true"
  28. @blur="isFocused = false"
  29. />
  30. <span
  31. v-if="$slots.default || label"
  32. :class="ns.be('button', 'inner')"
  33. :style="isChecked ? activeStyle : undefined"
  34. >
  35. <slot>{{ label }}</slot>
  36. </span>
  37. </label>
  38. </template>
  39. <script lang="ts" setup>
  40. import { computed, inject, useSlots } from 'vue'
  41. import { useNamespace } from '@element-plus/hooks'
  42. import { checkboxGroupContextKey } from './constants'
  43. import { useCheckbox } from './composables'
  44. import { checkboxEmits, checkboxProps } from './checkbox'
  45. import type { CSSProperties } from 'vue'
  46. defineOptions({
  47. name: 'ElCheckboxButton',
  48. })
  49. const props = defineProps(checkboxProps)
  50. defineEmits(checkboxEmits)
  51. const slots = useSlots()
  52. const {
  53. isFocused,
  54. isChecked,
  55. isDisabled,
  56. checkboxButtonSize,
  57. model,
  58. handleChange,
  59. } = useCheckbox(props, slots)
  60. const checkboxGroup = inject(checkboxGroupContextKey, undefined)
  61. const ns = useNamespace('checkbox')
  62. const activeStyle = computed<CSSProperties>(() => {
  63. const fillValue = checkboxGroup?.fill?.value ?? ''
  64. return {
  65. backgroundColor: fillValue,
  66. borderColor: fillValue,
  67. color: checkboxGroup?.textColor?.value ?? '',
  68. boxShadow: fillValue ? `-1px 0 0 0 ${fillValue}` : undefined,
  69. }
  70. })
  71. const labelKls = computed(() => {
  72. return [
  73. ns.b('button'),
  74. ns.bm('button', checkboxButtonSize.value),
  75. ns.is('disabled', isDisabled.value),
  76. ns.is('checked', isChecked.value),
  77. ns.is('focus', isFocused.value),
  78. ]
  79. })
  80. </script>