AppDropdown.vue 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <script setup>
  2. import { computed } from 'vue'
  3. const props = defineProps({
  4. label: {
  5. type: String,
  6. required: true,
  7. },
  8. disabled: {
  9. type: Boolean,
  10. default: false,
  11. },
  12. placeholder: {
  13. type: String,
  14. required: true,
  15. },
  16. error: {
  17. type: String,
  18. default: null,
  19. },
  20. optionLabel: {
  21. type: String,
  22. default: 'label',
  23. },
  24. optionValue: {
  25. type: String,
  26. default: 'value',
  27. },
  28. optionDisabled: {
  29. type: String,
  30. default: 'disabled',
  31. },
  32. optionGroupChildren: {
  33. type: String,
  34. default: null,
  35. },
  36. optionGroupLabel: {
  37. type: String,
  38. default: null,
  39. },
  40. options: {
  41. type: Array,
  42. required: true,
  43. },
  44. modelValue: null,
  45. })
  46. defineEmits(['update:modelValue'])
  47. const isError = computed(() => (props.error ? true : false))
  48. const forLabel = computed(() => (props.label ? props.label.toLowerCase().replace(/\s+/g, '-') : null))
  49. const ariaDescribedbyLabel = computed(() =>
  50. props.label ? props.label.toLowerCase().replace(/\s+/g, '-') + '-help' : null
  51. )
  52. const selectedDropdownLabel = (value) => {
  53. const result = props.options.find((option) => option[props.optionValue] == value)
  54. if (result) {
  55. return result[props.optionLabel]
  56. }
  57. }
  58. </script>
  59. <template>
  60. <div class="field">
  61. <label v-if="label" :for="forLabel">{{ label }}</label>
  62. <Dropdown
  63. class="w-full"
  64. :class="{ 'p-invalid': isError }"
  65. :id="forLabel"
  66. :aria-describedby="ariaDescribedbyLabel"
  67. :option-disabled="optionDisabled"
  68. :option-group-children="optionGroupChildren"
  69. :option-group-label="optionGroupLabel"
  70. :option-label="optionLabel"
  71. :option-value="optionValue"
  72. :placeholder="placeholder"
  73. :options="options"
  74. :model-value="modelValue"
  75. :disabled="disabled"
  76. @change="$emit('update:modelValue', $event.value)"
  77. >
  78. <template #value="slotProps">
  79. <div v-if="slotProps.value">
  80. {{ selectedDropdownLabel(slotProps.value) }}
  81. </div>
  82. <div v-else>
  83. {{ slotProps.placeholder }}
  84. </div>
  85. </template>
  86. <template #option="{ option, index }">
  87. <slot name="option" :option="option" :index="index" />
  88. </template>
  89. </Dropdown>
  90. <small v-if="error" :id="ariaDescribedbyLabel" :class="{ 'p-error': isError }">
  91. {{ error }}
  92. </small>
  93. </div>
  94. </template>