AppDropdown.vue 1.9KB

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