当前位置: 首页 > news >正文

封装el-autocomplete,接口调用

组件

<template><el-autocompletev-model="selectedValue":fetch-suggestions="fetchSuggestions":placeholder="placeholder"@select="handleSelect"clearablev-bind="$attrs"/>
</template><script lang="ts" setup>
import { ref, computed, onMounted, withDefaults } from 'vue'
import type { AutocompleteProps, AutocompleteEmits } from 'element-plus'interface AutocompleteItem {value: string[key: string]: any
}interface Props {placeholder?: stringdebounce?: numberapiFn?: (query: string) => Promise<AutocompleteItem[]> // 模拟接口函数localData?: AutocompleteItem[] // 本地数据filterFn?: (query: string, item: AutocompleteItem) => boolean // 自定义过滤函数
}const props = withDefaults(defineProps<Props>(), {placeholder: '请输入内容',debounce: 300,localData: () => [],filterFn: undefined
})const emit = defineEmits<{(e: 'update:modelValue', value: string): void(e: 'select', item: AutocompleteItem): void
}>()const selectedValue = ref('')
const loading = ref(false)
const suggestions = ref<AutocompleteItem[]>([])
let timeout: number | undefined// 默认过滤函数 - 开头匹配(不区分大小写)
const defaultFilter = (query: string) => {const lowerQuery = query.toLowerCase()return (item: AutocompleteItem) => item.value.toLowerCase().startsWith(lowerQuery)
}// 模拟接口获取数据
const mockApiFetch = async (query: string): Promise<AutocompleteItem[]> => {// 这里模拟API请求延迟await new Promise(resolve => setTimeout(resolve, 500))// 模拟数据const mockData = [{ value: 'Vue', link: 'https://vuejs.org' },{ value: 'React', link: 'https://reactjs.org' },{ value: 'Angular', link: 'https://angular.io' },{ value: 'Svelte', link: 'https://svelte.dev' },{ value: 'TypeScript', link: 'https://www.typescriptlang.org' },]// 模拟接口过滤return mockData.filter(item => item.value.toLowerCase().includes(query.toLowerCase()))
}// 获取建议列表
const fetchSuggestions = async (query: string, cb: (arg: AutocompleteItem[]) => void
) => {clearTimeout(timeout)if (!query) {cb(props.localData)return}loading.value = truetimeout = setTimeout(async () => {try {let results: AutocompleteItem[] = []if (props.apiFn) {// 使用传入的接口函数获取数据results = await props.apiFn(query)} else if (props.localData.length) {// 使用本地数据过滤const filter = props.filterFn ? (item: AutocompleteItem) => props.filterFn!(query, item): defaultFilter(query)results = props.localData.filter(filter)} else {// 使用默认模拟接口results = await mockApiFetch(query)}suggestions.value = resultscb(results)} catch (error) {console.error('获取建议列表失败:', error)cb([])} finally {loading.value = false}}, props.debounce) as unknown as number
}// 选择事件
const handleSelect = (item: AutocompleteItem) => {emit('update:modelValue', item.value)emit('select', item)
}// 暴露方法
defineExpose({focus: () => {// 这里可以访问el-autocomplete的方法// 需要在实际使用时通过ref获取组件实例}
})
</script><style scoped>
.el-autocomplete {width: 100%;
}
</style>

基本用法(使用内置模拟接口)

<template><CustomAutocomplete v-model="selectedValue" />
</template><script setup lang="ts">
import { ref } from 'vue'
import CustomAutocomplete from './CustomAutocomplete.vue'const selectedValue = ref('')
</script>

使用自定义接口函数

<template><CustomAutocomplete v-model="selectedValue":api-fn="fetchDataFromApi"/>
</template><script setup lang="ts">
import { ref } from 'vue'
import CustomAutocomplete from './CustomAutocomplete.vue'const selectedValue = ref('')const fetchDataFromApi = async (query: string) => {// 这里可以替换为真实的API调用console.log('查询:', query)return [{ value: `${query}-结果1`, id: 1 },{ value: `${query}-结果2`, id: 2 }]
}
</script>

自定义过滤逻辑

<template><CustomAutocomplete v-model="selectedValue":local-data="techList":filter-fn="customFilter"/>
</template><script setup lang="ts">
import { ref } from 'vue'
import CustomAutocomplete from './CustomAutocomplete.vue'const selectedValue = ref('')
const techList = ref([{ value: 'Vue.js', category: 'frontend' },{ value: 'React', category: 'frontend' },{ value: 'Express', category: 'backend' }
])const customFilter = (query: string, item: any) => {// 同时匹配value和categoryreturn item.value.toLowerCase().includes(query.toLowerCase()) || item.category.toLowerCase().includes(query.toLowerCase())
}
</script>

相关文章:

  • 蓝桥杯 11. 打印大X
  • 手搓传染病模型(SEIR)
  • 2025年AEJ SCI2区:增强麻雀搜索算法CERL-SSA+工业物联网感知通信,深度解析+性能实测
  • 视觉导航中的滑动窗口
  • C++ RAII
  • 使用 Autofac 实现依赖注入
  • Redis缓存问题的深度解析与解决方案
  • C语言实现迪杰斯特拉算法进行路径规划
  • Java 面向对象:多态详解及各种用法
  • AI实战SEO关键词优化法
  • 昇腾大模型训推平台厂商介绍
  • 【Node.js 】在Windows 下搭建适配 DPlayer 的轻量(简陋)级弹幕后端服务
  • Redis哨兵模式深度解析:实现高可用与自动故障转移的终极指南
  • 双指针算法(2)——复写零
  • 天梯——现代战争
  • 基于STM32、HAL库的ADS1115模数转换器ADC驱动程序设计
  • AntBio: 2025 AACR Meeting - Charting New Oncology Frontiers Together
  • google chrome 中 fcitx5 候选框不跟随光标
  • `==` 和 `===` 的隐式转换规则总结
  • 直播预告|TinyVue 组件库高级用法:定制你的企业级UI体系
  • 深圳一季度GDP为8950.49亿元,同比增长5.2%
  • 《沙尘暴》:用贴近生活的影像和表演拍摄悬疑剧
  • “下山虎”张名扬一回合摘下“狮心”:你们再嘘一个给我听听
  • 乌方称泽连斯基与特朗普进行简短会谈
  • 机票搜索热度飙升,透过数据看五一假期旅游热度
  • 现场观察·国防部记者会|美将举行大演习“应对中国”,备战太平洋引发关注