remote-search.vue 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <template>
  2. <el-autocomplete
  3. v-model="state"
  4. :fetch-suggestions="querySearchAsync"
  5. placeholder="Please input"
  6. @select="handleSelect"
  7. />
  8. </template>
  9. <script lang="ts" setup>
  10. import { onMounted, ref } from 'vue'
  11. const state = ref('')
  12. interface LinkItem {
  13. value: string
  14. link: string
  15. }
  16. const links = ref<LinkItem[]>([])
  17. const loadAll = () => {
  18. return [
  19. { value: 'vue', link: 'https://github.com/vuejs/vue' },
  20. { value: 'element', link: 'https://github.com/ElemeFE/element' },
  21. { value: 'cooking', link: 'https://github.com/ElemeFE/cooking' },
  22. { value: 'mint-ui', link: 'https://github.com/ElemeFE/mint-ui' },
  23. { value: 'vuex', link: 'https://github.com/vuejs/vuex' },
  24. { value: 'vue-router', link: 'https://github.com/vuejs/vue-router' },
  25. { value: 'babel', link: 'https://github.com/babel/babel' },
  26. ]
  27. }
  28. let timeout: NodeJS.Timeout
  29. const querySearchAsync = (queryString: string, cb: (arg: any) => void) => {
  30. const results = queryString
  31. ? links.value.filter(createFilter(queryString))
  32. : links.value
  33. clearTimeout(timeout)
  34. timeout = setTimeout(() => {
  35. cb(results)
  36. }, 3000 * Math.random())
  37. }
  38. const createFilter = (queryString: string) => {
  39. return (restaurant: LinkItem) => {
  40. return (
  41. restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
  42. )
  43. }
  44. }
  45. const handleSelect = (item: LinkItem) => {
  46. console.log(item)
  47. }
  48. onMounted(() => {
  49. links.value = loadAll()
  50. })
  51. </script>