index.vue 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <template>
  2. <t-select
  3. v-model="selected"
  4. filterable
  5. clearable
  6. v-bind="attrs"
  7. @change="onChange"
  8. >
  9. <t-option
  10. v-for="item in optionList"
  11. :key="item.id"
  12. :value="item.id"
  13. :label="item.name"
  14. />
  15. </t-select>
  16. </template>
  17. <script setup name="SelectProduct">
  18. import { onMounted, ref, useAttrs, watch, computed } from 'vue';
  19. import { productListApi } from '@/api/service-unit';
  20. let optionList = ref([]);
  21. let selected = ref('');
  22. const attrs = useAttrs();
  23. const emit = defineEmits(['update:modelValue', 'change']);
  24. const props = defineProps({
  25. modelValue: { type: [Number, String, Array], default: '' },
  26. });
  27. const isMultiple = computed(() => {
  28. const multiple = attrs.multiple;
  29. return multiple === '' || multiple;
  30. });
  31. const search = async () => {
  32. optionList.value = [];
  33. let data = { enable: true };
  34. const res = await productListApi(data).catch(() => {});
  35. if (!res) return;
  36. optionList.value = res;
  37. };
  38. const onChange = () => {
  39. const selectedData = isMultiple.value
  40. ? optionList.value.filter(
  41. (item) => selected.value && selected.value.includes(item.id)
  42. )
  43. : optionList.value.filter((item) => selected.value === item.id);
  44. emit('update:modelValue', selected.value);
  45. emit('change', isMultiple.value ? selectedData : selectedData[0]);
  46. };
  47. onMounted(() => {
  48. search();
  49. });
  50. watch(
  51. () => props.modelValue,
  52. (val) => {
  53. selected.value = val;
  54. }
  55. );
  56. </script>