现在很多软件的搜索栏都会有历史搜索,比如淘宝京东,类似下图:
这里我们也来开发一个类似的东西
先看看效果
这里的搜索词回保存起来,并且历史记录的外框根据长度变化,当长度不够一行的时候进行自动换行。
看看代码
- WXML
<van-search model:value="{{ value }}" shape="round" placeholder="请输入委托单位名称" background="white" use-action-slot
bind:search="onSearch">
<view slot="action" class="action-text" bind:tap="onSearch">查询</view>
</van-search>
<view class="container">
<view class="history-title row">
<text class="flex1">历史搜索</text>
<van-icon custom-class="iconfont iconshanchu" size="28rpx" bind:click="onClear" />
</view>
<view class="history-container">
<text class="history-item" wx:for='{{history}}' wx:key='this' data-index='{{index}}' bindtap="onSelect">{{item}}</text>
</view>
</view>
代码很少也很简单,就是一个有赞的搜索框,一个历史搜索的提示词,一个历史搜索的容器,里面通过循环生成历史搜索词。这里的有赞搜索框用了 slot ,它原来右边那个字是清除文字,点击会触发清除事件,不太行。
- WXSS
.container {
padding: 40rpx 32rpx;
}
.history-title {
font-size: 28rpx;
font-family: PingFangSC-Regular, PingFang SC;
font-weight: 400;
color: #616161;
line-height: 40rpx;
}
.history-container {
margin-top: 24rpx;
}
.history-item {
display: inline-block;
border-radius: 24rpx;
border: 1px solid #E5E5E5;
padding: 4rpx 20rpx;
box-sizing: border-box;
font-size: 28rpx;
font-family: PingFangSC-Regular, PingFang SC;
font-weight: 400;
color: #616161;
margin-top: 16rpx;
margin-right: 16rpx;
}
.action-text {
font-size: 32rpx;
font-family: PingFangSC-Regular, PingFang SC;
font-weight: 400;
color: #2E2E2E;
line-height: 44rpx;
}
实际整个功能的重点就在 WXSS 里面,只需要将历史搜索词的样式设置为 display: inline-block; 就会自动换行了,这个没用过之前可是难到了我。至于为什么是 display: inline-block; 而不是 inline,就是因为这里还要有上边距,当然使用 line-height 也可以吧,可以试试。
- Page.js
Page({
data: {
value: '',
history: [],
},
onLoad: function (options) {
let that = this
wx.getStorage({
key: 'SearchHistory',
success(res) {
that.setData({
history: res.data
})
}
})
},
onSearch(e) {
//保存搜索记录
let value = this.data.value
let history = this.data.history
//如果已经存在删除再插入到最后
let index = -1
for (let i = 0; i < history.length; i++) {
let temp = history[i]
if (value == temp) {
index = i
break
}
}
if (index >= 0) {
history.splice(index, 1)
}
//最后一个搜索词
if(value!='') {
history.push(value)
}
this.setData({
history: history
})
//跳转到结果页面
wx.navigateTo({
url: '../../../you/url/path/',
})
//异步保存即可
wx.setStorage({
key: "SearchHistory",
data: this.data.history
})
},
onSelect(e) {
let index = e.currentTarget.dataset.index
let word = this.data.history[index]
if(word!=this.data.value) {
this.setData({
value: word
})
}
//直接跳转搜索
this.onSearch()
},
onClear(e) {
this.setData({
history: []
})
wx.setStorage({
key: "SearchHistory",
data: []
})
}
})
页面代码实际没什么好说的,就是需要将历史数据储存和载入,和之前写的历史用户来说都是小意思了。
结语
东西很简单,但是没有想到解决办法之前还是没有思绪的。
end
完美撒花