uniapp 搜索
uniapp 搜索功能实现方法
全局搜索组件集成
在pages.json中配置全局搜索栏,适用于所有页面顶部显示搜索框。示例代码:
"globalStyle": {
"navigationBarTextStyle": "black",
"navigationBarTitleText": "uni-app",
"navigationBarBackgroundColor": "#F8F8F8",
"backgroundColor": "#F8F8F8",
"app-plus": {
"titleNView": {
"searchInput": {
"align": "center",
"backgroundColor": "#fff",
"borderRadius": "12px",
"placeholder": "请输入搜索内容",
"disabled": false
}
}
}
}
页面级搜索框实现
使用uni-search-bar组件实现单页面搜索功能,支持实时搜索和取消操作:
<template>
<view>
<uni-search-bar
@confirm="search"
@input="input"
@cancel="cancel"
placeholder="商品搜索">
</uni-search-bar>
</view>
</template>
搜索逻辑处理
通过@input事件实现实时搜索建议,使用防抖函数优化性能:
let timer = null
methods: {
input(e) {
clearTimeout(timer)
timer = setTimeout(() => {
this.getSuggestions(e)
}, 500)
},
getSuggestions(keyword) {
uni.request({
url: 'https://api.example.com/search',
data: { keyword },
success: (res) => {
this.suggestions = res.data.list
}
})
}
}
历史记录存储
使用uni.setStorageSync保存搜索历史,并支持本地缓存管理:
saveHistory(keyword) {
let histories = uni.getStorageSync('searchHistory') || []
if (!histories.includes(keyword)) {
histories.unshift(keyword)
uni.setStorageSync('searchHistory', histories.slice(0, 10))
}
}
搜索结果页设计
建议采用分页加载模式,结合uni-load-more组件实现无限滚动:
<scroll-view
scroll-y
@scrolltolower="loadMore"
style="height: calc(100vh - 100px)">
<view v-for="item in list" :key="item.id">
<!-- 结果项内容 -->
</view>
<uni-load-more :status="loadingStatus"></uni-load-more>
</scroll-view>
多端适配方案
通过条件编译处理各平台差异:
// #ifdef APP-PLUS
this.adjustSearchBarPosition()
// #endif
// #ifdef H5
this.initH5SearchEvent()
// #endif






