实现效果如下
聚焦显示历史记录
关联历史记录
注意点
结构上需要将input框和下面的historyList作为一个整体,可自行控制展示历史记录的规格;
使用微信缓存API wx.getStorageSync 和wx.setStorageSync,处理历史记录的存储时记得去重
WXML结构
<view class="search-box">
<image class="search-icon" src="./images/searchIcon.png" ></image>
<input class="hd-search" placeholder="请输入搜索关键词"
bindconfirm="searchMsg"
bindfocus="showHistory"
bindblur="clearList"
bindinput="findHistory"
value="{{inputText}}"
focus="{{isFocus}}"></input>
<!--历史记录!-->
<view class="search-history-item"
wx:for="{{searchList}}" wx:key="index"
bindtap="reSearch"
data-text="{{item}}">
{{item}}
</view>
</view>
WXSS
.search-box {
width: 700rpx;
position: absolute;
padding-left: 80rpx;
padding-right: 80rpx;
top: 340rpx;
left: 50%;
z-index: 2;
transform: translateX(-50%);
align-items: center;
font-family: PingFangSC-Regular;
font-size: 28rpx;
border-radius: 60rpx;
background-color: #fff;
box-sizing: border-box;
box-shadow: 0rpx 2rpx 12rpx 0rpx rgba(218,224,229,1);
}
.hd-search {
width: 100%;
height: 80rpx;
}
.search-icon {
width: 40rpx;
height: 40rpx;
position: absolute;
top: 20rpx;
left: 22rpx;
}
.search-history-item {
height: 60rpx;
overflow: hidden;
}
JS
data: {
searchList:[],
inputText:'',
isFocus:false
},
searchMsg(option){
// option.detail.value
const that = this
// 回车值入缓存
if(option.detail.value != ''){
try {
let value = wx.getStorageSync('history')
if(value){
// 最多缓存20条记录
that.data.searchList = JSON.parse(value).slice(0,20)
}
//去重
let index = this.data.searchList.indexOf(option.detail.value)
if(index > -1){
this.data.searchList.splice(index,1)
}
that.data.searchList.unshift(option.detail.value)
wx.setStorageSync('history', JSON.stringify(that.data.searchList))
}catch(e){
console.log(e)
}
// 搜索成功后跳转页面,并清空searchList
this.clearList()
}
},
// 聚焦且无输入值时显示所有历史记录,有输入值时显示包含其的所有历史记录
showHistory(option){
// option.detail.value
//获取缓存数据
const that = this
if(!option.detail.value){
try {
let value = wx.getStorageSync('history')
if (value) {
that.setData({
// 只展示5个
searchList:JSON.parse(value).slice(0,5)
})
}
} catch (e) {
}
}else {
this.findHistory('',option.detail.value)
}
},
//点击历史记录进行填充搜索
reSearch(e){
// e.currentTarget.dataset.text
this.setData({
inputText:e.currentTarget.dataset.text,
// 这个聚焦方法会出现闪动的情况
isFocus:true
})
},
clearList(){
this.setData({
searchList:[]
})
},
// 查找搜索历史记录
findHistory(e,param){
// e.detail.value
const that = this
let temp = []
let p = param ? param : e.detail.value
if(p){
try{
let value = wx.getStorageSync('history')
if(value){
JSON.parse(value).forEach((item,index)=>{
if(item.indexOf(p) > -1){
temp.unshift(item)
}
})
}
}catch(e){
console.log(e)
}
}else {
temp = JSON.parse(wx.getStorageSync('history')).slice(0,5)
}
that.setData({
searchList:temp
})
},