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

封装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>

http://www.xdnf.cn/news/2617.html

相关文章:

  • Ubuntu安装brew
  • OSI 模型(开放系统互联模型)
  • FEKO许可安装
  • CCF推荐学术会议-C(网络与信息安全):SAC 2025
  • Python学习之路(六)-图像识别
  • 数字化转型的未来趋势:从工具到生态,聚焦生态合作、绿色转型与全球化布局
  • Vue3 Element Plus el-tabs数据刷新方法
  • 更快的图像局部修改与可控生成:Flex.2-preview
  • 航顺 芯片 开发记录 (一) 2025年4月27日19:23:32
  • 【博客系统】博客系统第二弹:实现博客列表接口
  • T检验、F检验及样本容量计算学习总结
  • 通过示例学习:连续 XOR
  • SpringBoot驾校报名小程序实现
  • 详细PostMan的安装和基本使用方法
  • 【SF】在 Android 显示系统中,图层合成方式 Device 和 Client 的区别
  • 文章记单词 | 第50篇(六级)
  • Zookeeper HA集群搭建
  • 昂瑞微蓝牙OM6621系列对比选型指南
  • 《代码整洁之道》第8章 边界 - 笔记
  • NCCL 通信与调试
  • Grok发布了Grok Studio 和 Workspaces两个强大的功能。该如何使用?如何使用Grok3 API?
  • 深度学习与SLAM特征提取融合:技术突破与应用前景
  • 深入解读:2025 数字化转型管理 参考架构
  • 视频HLS分片与关键帧优化深度解析
  • 2025 网络安全技术深水区探索:从 “攻防对抗” 到 “数字韧性” 的范式跃迁
  • VRRP与BFD在冗余设计中的核心区别:从“备用网关”到“毫秒级故障检测”
  • JavaScript中主动抛出错误的方法
  • 【java】lambda表达式总结
  • 类-python
  • AI中Token的理解与使用总结