uniapp搜索框功能
uniapp 搜索框功能实现
在 uniapp 中实现搜索框功能可以通过多种方式完成,以下是一些常见的方法和示例代码:
基础搜索框实现
使用 uni-easyinput 组件或原生 input 元素结合搜索按钮:

<template>
<view>
<uni-easyinput
v-model="searchText"
placeholder="请输入搜索内容"
@confirm="handleSearch"
>
<template #right>
<button @click="handleSearch">搜索</button>
</template>
</uni-easyinput>
</view>
</template>
<script>
export default {
data() {
return {
searchText: ''
}
},
methods: {
handleSearch() {
uni.showToast({
title: '搜索:' + this.searchText,
icon: 'none'
})
// 实际搜索逻辑
}
}
}
</script>
防抖优化
对于频繁触发的搜索(如实时搜索),建议添加防抖处理:
let timer = null
methods: {
handleSearch() {
clearTimeout(timer)
timer = setTimeout(() => {
this.performSearch()
}, 500)
},
performSearch() {
// 实际搜索逻辑
}
}
搜索历史记录
添加搜索历史存储功能:

methods: {
saveSearchHistory() {
let history = uni.getStorageSync('searchHistory') || []
history.unshift(this.searchText)
history = [...new Set(history)].slice(0, 10)
uni.setStorageSync('searchHistory', history)
}
}
接口请求示例
结合后端接口的搜索实现:
async performSearch() {
try {
const res = await uni.request({
url: 'https://api.example.com/search',
data: {
keyword: this.searchText
}
})
// 处理返回结果
} catch (error) {
uni.showToast({
title: '搜索失败',
icon: 'none'
})
}
}
样式自定义
通过 CSS 自定义搜索框样式:
.custom-search {
display: flex;
padding: 10px;
background-color: #f5f5f5;
border-radius: 20px;
}
.custom-search input {
flex: 1;
padding: 0 10px;
}
注意事项
- 在微信小程序中,input 组件需要添加
confirm-type="search"属性才能触发键盘的搜索按钮 - 考虑添加 loading 状态提升用户体验
- 对于复杂搜索条件,可以设计单独的搜索页面
- 移动端注意软键盘的处理,可能需要手动控制收起
以上实现可以根据具体需求进行组合和扩展,uniapp 的跨平台特性保证了这些代码在多数平台都能正常运行。






