uniapp搜索框组件
uniapp 搜索框组件实现方法
在 uniapp 中实现搜索框功能,可以通过内置组件或第三方插件完成。以下是几种常见的实现方式:
使用 uni-ui 的 SearchBar 组件
uni-ui 提供了现成的搜索框组件,安装后可直接使用。在 pages.json 中配置:
{
"easycom": {
"autoscan": true,
"custom": {
"^uni-(.*)": "@dcloudio/uni-ui/lib/uni-$1/uni-$1.vue"
}
}
}
页面中使用示例:
<template>
<uni-search-bar
placeholder="请输入搜索内容"
@confirm="search"
@input="input"
@cancel="cancel">
</uni-search-bar>
</template>
自定义搜索框组件
通过组合 view 和 input 元素实现自定义搜索框:
<template>
<view class="search-box">
<input
class="search-input"
placeholder="搜索"
v-model="keyword"
@confirm="handleSearch"
@input="handleInput"/>
<button @click="handleSearch">搜索</button>
</view>
</template>
样式示例:
.search-box {
display: flex;
padding: 10px;
background: #f5f5f5;
}
.search-input {
flex: 1;
height: 36px;
padding: 0 10px;
background: #fff;
border-radius: 4px;
}
使用第三方插件
uView UI 等第三方组件库也提供搜索框组件:
<template>
<u-search
placeholder="请输入关键字"
v-model="keyword"
:show-action="true"
@search="onSearch"
@custom="onCustom">
</u-search>
</template>
搜索功能实现要点
防抖处理 高频输入场景建议使用防抖函数:
let timer = null
function handleInput(e) {
clearTimeout(timer)
timer = setTimeout(() => {
this.searchApi(e.detail.value)
}, 500)
}
搜索历史记录 本地存储搜索记录示例:
function saveSearchHistory(keyword) {
let history = uni.getStorageSync('searchHistory') || []
history.unshift(keyword)
history = [...new Set(history)].slice(0, 10)
uni.setStorageSync('searchHistory', history)
}
接口调用 结合后端API实现搜索:
async function searchApi(keyword) {
try {
const res = await uni.request({
url: '/api/search',
data: { keyword }
})
this.resultList = res.data
} catch (e) {
console.error(e)
}
}
平台适配注意事项
- iOS平台需注意软键盘的"搜索"按钮事件
- 安卓平台需处理返回键关闭搜索页面的逻辑
- 小程序平台需注意输入框聚焦状态样式
- H5平台需考虑回车键触发搜索
通过以上方法可以快速在 uniapp 项目中实现功能完善的搜索框组件,根据实际需求选择适合的实现方案。







