autocomplete.vue 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <template>
  2. <el-row class="demo-autocomplete">
  3. <el-col :span="12">
  4. <div class="sub-title my-2 text-sm text-gray-600">
  5. list suggestions when activated
  6. </div>
  7. <el-autocomplete
  8. v-model="state1"
  9. :fetch-suggestions="querySearch"
  10. clearable
  11. class="inline-input w-50"
  12. placeholder="Please Input"
  13. @select="handleSelect"
  14. />
  15. </el-col>
  16. <el-col :span="12">
  17. <div class="sub-title my-2 text-sm text-gray-600">
  18. list suggestions on input
  19. </div>
  20. <el-autocomplete
  21. v-model="state2"
  22. :fetch-suggestions="querySearch"
  23. :trigger-on-focus="false"
  24. clearable
  25. class="inline-input w-50"
  26. placeholder="Please Input"
  27. @select="handleSelect"
  28. />
  29. </el-col>
  30. </el-row>
  31. </template>
  32. <script lang="ts" setup>
  33. import { onMounted, ref } from 'vue'
  34. interface RestaurantItem {
  35. value: string
  36. link: string
  37. }
  38. const state1 = ref('')
  39. const state2 = ref('')
  40. const restaurants = ref<RestaurantItem[]>([])
  41. const querySearch = (queryString: string, cb: any) => {
  42. const results = queryString
  43. ? restaurants.value.filter(createFilter(queryString))
  44. : restaurants.value
  45. // call callback function to return suggestions
  46. cb(results)
  47. }
  48. const createFilter = (queryString: string) => {
  49. return (restaurant: RestaurantItem) => {
  50. return (
  51. restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
  52. )
  53. }
  54. }
  55. const loadAll = () => {
  56. return [
  57. { value: 'vue', link: 'https://github.com/vuejs/vue' },
  58. { value: 'element', link: 'https://github.com/ElemeFE/element' },
  59. { value: 'cooking', link: 'https://github.com/ElemeFE/cooking' },
  60. { value: 'mint-ui', link: 'https://github.com/ElemeFE/mint-ui' },
  61. { value: 'vuex', link: 'https://github.com/vuejs/vuex' },
  62. { value: 'vue-router', link: 'https://github.com/vuejs/vue-router' },
  63. { value: 'babel', link: 'https://github.com/babel/babel' },
  64. ]
  65. }
  66. const handleSelect = (item: RestaurantItem) => {
  67. console.log(item)
  68. }
  69. onMounted(() => {
  70. restaurants.value = loadAll()
  71. })
  72. </script>