remote-search.vue 1.5 KB

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