uniapp 搜索
uniapp 搜索功能实现方法
在 uniapp 中实现搜索功能可以通过多种方式,包括本地搜索和远程搜索。以下是几种常见的实现方法:
本地搜索
使用 uniapp 的 filter 方法或 computed 属性对本地数据进行筛选。适用于数据量较小的场景。
<template>
<view>
<input v-model="searchText" placeholder="请输入搜索内容" />
<view v-for="item in filteredList" :key="item.id">
{{ item.name }}
</view>
</view>
</template>
<script>
export default {
data() {
return {
searchText: '',
list: [
{ id: 1, name: '苹果' },
{ id: 2, name: '香蕉' },
{ id: 3, name: '橙子' }
]
}
},
computed: {
filteredList() {
return this.list.filter(item => {
return item.name.includes(this.searchText)
})
}
}
}
</script>
远程搜索 通过调用接口实现搜索功能,适用于数据量较大的场景。
<script>
export default {
data() {
return {
searchText: '',
resultList: []
}
},
methods: {
async search() {
const res = await uni.request({
url: 'https://example.com/api/search',
data: {
keyword: this.searchText
}
})
this.resultList = res.data
}
}
}
</script>
防抖优化 对于远程搜索,可以使用防抖函数减少请求次数。
<script>
export default {
data() {
return {
timer: null,
searchText: '',
resultList: []
}
},
watch: {
searchText(val) {
clearTimeout(this.timer)
this.timer = setTimeout(() => {
this.search()
}, 500)
}
},
methods: {
async search() {
const res = await uni.request({
url: 'https://example.com/api/search',
data: {
keyword: this.searchText
}
})
this.resultList = res.data
}
}
}
</script>
搜索历史记录 可以结合本地存储实现搜索历史记录功能。

<script>
export default {
data() {
return {
searchText: '',
historyList: []
}
},
onLoad() {
this.historyList = uni.getStorageSync('searchHistory') || []
},
methods: {
search() {
if (!this.searchText) return
this.historyList.unshift(this.searchText)
uni.setStorageSync('searchHistory', this.historyList)
// 执行搜索逻辑
}
}
}
</script>
注意事项
- 对于大量数据搜索,建议使用分页加载
- 移动端搜索框建议添加防抖或节流功能
- 搜索结果为空时,应显示友好的提示信息
- 搜索功能应考虑网络异常情况的处理






