AppDropdown.vue 2.0KB

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