AutocompleteWithAPI.vue 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <!--
  2. Liste déroulante avec autocompletion (les données sont issues
  3. d'une api)
  4. @see https://vuetifyjs.com/en/components/autocompletes/#usage
  5. -->
  6. <template>
  7. <main>
  8. <UiInputAutocomplete
  9. :field="field"
  10. :label="label"
  11. :data="data"
  12. :items="items"
  13. :isLoading="isLoading"
  14. :item-text="itemText"
  15. :slotText="slotText"
  16. :item-value="itemValue"
  17. prependIcon="mdi-magnify"
  18. :return-object="returnObject"
  19. @research="search"
  20. :no-filter="noFilter"
  21. @update="$emit('update', $event, field)"
  22. />
  23. </main>
  24. </template>
  25. <script lang="ts">
  26. import {defineComponent, ref, Ref, watch, onUnmounted, toRefs} from '@nuxtjs/composition-api'
  27. export default defineComponent({
  28. props: {
  29. label: {
  30. type: String,
  31. required: false,
  32. default: null
  33. },
  34. field: {
  35. type: String,
  36. required: false,
  37. default: null
  38. },
  39. searchFunction: {
  40. type: Function,
  41. required: true
  42. },
  43. data: {
  44. type: [String, Number, Object, Array],
  45. required: false,
  46. default: null
  47. },
  48. readonly: {
  49. type: Boolean,
  50. required: false
  51. },
  52. itemValue: {
  53. type: String,
  54. default: 'id'
  55. },
  56. itemText: {
  57. type: Array,
  58. required: true
  59. },
  60. slotText: {
  61. type: Array,
  62. required: false
  63. },
  64. returnObject: {
  65. type: Boolean,
  66. default: false
  67. },
  68. noFilter: {
  69. type: Boolean,
  70. default: false
  71. }
  72. },
  73. setup(props) {
  74. const {data} = toRefs(props)
  75. const items:Ref<Array<any>> = ref([data.value])
  76. const isLoading = ref(false)
  77. const search = async (research:string) => {
  78. isLoading.value = true
  79. const func: Function = props.searchFunction
  80. items.value = await func(research, props.field)
  81. isLoading.value = false
  82. }
  83. const unwatch = watch(data,(d) => {
  84. items.value = [d]
  85. })
  86. onUnmounted(() => {
  87. unwatch()
  88. })
  89. return {
  90. label_field: props.label ?? props.field,
  91. isLoading,
  92. items,
  93. search
  94. }
  95. }
  96. })
  97. </script>