UnitSelect.vue 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <template>
  2. <DefaultSelect
  3. v-model="selectedUnit"
  4. v-bind="$attrs"
  5. use-input
  6. hide-selected
  7. fill-input
  8. clearable
  9. :options="filteredOptions"
  10. :loading="isLoading"
  11. :placeholder
  12. :label
  13. @filter="filterFn"
  14. >
  15. <template #no-option>
  16. <q-item>
  17. <q-item-section class="text-grey">
  18. {{ $t("http.errors.no_records_found") }}
  19. </q-item-section>
  20. </q-item>
  21. </template>
  22. </DefaultSelect>
  23. </template>
  24. <script setup>
  25. import { onMounted, ref, watch } from "vue";
  26. import { getUnitsForSelect } from "src/api/unit";
  27. import DefaultSelect from "src/components/defaults/DefaultSelect.vue";
  28. const { placeholder, label, initialId } = defineProps({
  29. placeholder: { type: String, default: "Buscar unidade" },
  30. label: { type: String, default: "Unidade" },
  31. initialId: { type: Number, default: null },
  32. });
  33. const selectedUnit = defineModel({ type: Object });
  34. const unitOptions = ref([]);
  35. const filteredOptions = ref([]);
  36. const isLoading = ref(true);
  37. const selectUnitById = (id) => {
  38. selectedUnit.value = unitOptions.value.find((o) => o.value === id) ?? null;
  39. };
  40. const filterFn = (val, update) => {
  41. update(() => {
  42. if (val === "") {
  43. filteredOptions.value = unitOptions.value;
  44. } else {
  45. const needle = val.toLowerCase();
  46. filteredOptions.value = unitOptions.value.filter((v) =>
  47. v.label.toLowerCase().includes(needle),
  48. );
  49. }
  50. });
  51. };
  52. onMounted(async () => {
  53. try {
  54. const response = await getUnitsForSelect();
  55. unitOptions.value = response.map((unit) => ({
  56. label: unit.fantasy_name,
  57. value: unit.id,
  58. }));
  59. filteredOptions.value = unitOptions.value;
  60. if (initialId) selectUnitById(initialId);
  61. } catch (error) {
  62. console.error("Failed to load units:", error);
  63. } finally {
  64. isLoading.value = false;
  65. }
  66. });
  67. watch(
  68. () => initialId,
  69. (newId) => {
  70. if (newId && unitOptions.value.length > 0) {
  71. selectUnitById(newId);
  72. }
  73. },
  74. );
  75. defineExpose({ selectUnitById });
  76. </script>