UnitSelect.vue 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. import { formatUnitName } from "src/helpers/utils";
  29. const { placeholder, label, initialId } = defineProps({
  30. placeholder: { type: String, default: "Buscar unidade" },
  31. label: { type: String, default: "Unidade" },
  32. initialId: { type: Number, default: null },
  33. });
  34. const selectedUnit = defineModel({ type: Object });
  35. const unitOptions = ref([]);
  36. const filteredOptions = ref([]);
  37. const isLoading = ref(true);
  38. const selectUnitById = (id) => {
  39. selectedUnit.value = unitOptions.value.find((o) => o.value === id) ?? null;
  40. };
  41. const filterFn = (val, update) => {
  42. update(() => {
  43. if (val === "") {
  44. filteredOptions.value = unitOptions.value;
  45. } else {
  46. const needle = val.toLowerCase();
  47. filteredOptions.value = unitOptions.value.filter((v) =>
  48. v.label.toLowerCase().includes(needle),
  49. );
  50. }
  51. });
  52. };
  53. onMounted(async () => {
  54. try {
  55. const response = await getUnitsForSelect();
  56. unitOptions.value = response.map((unit) => ({
  57. label: formatUnitName(unit),
  58. value: unit.id,
  59. }));
  60. filteredOptions.value = unitOptions.value;
  61. if (initialId) selectUnitById(initialId);
  62. } catch (error) {
  63. console.error("Failed to load units:", error);
  64. } finally {
  65. isLoading.value = false;
  66. }
  67. });
  68. watch(
  69. () => initialId,
  70. (newId) => {
  71. if (newId && unitOptions.value.length > 0) {
  72. selectUnitById(newId);
  73. }
  74. },
  75. );
  76. defineExpose({ selectUnitById });
  77. </script>