要求
1、实现搜索框输入内容按下搜索按钮或回车后,将搜索框的内容存入本地,
2、以搜索历史记录的形式读取本地数据
3、添加一个清空历史记录的功能
html部分
<view>
<view class="x">
<u-search style=" border-radius: 20px;" placeholder="输入小区/商圈/地铁站等" actionText='' searchIcon=''
@search="Storage" v-model="setval"></u-search>
<view class="show">
<text style="color: #787C7D;">搜索历史</text>
<u-icon @click="historeDelete" name="trash" size="30" ></u-icon>
</view>
<view style="display: flex; margin-top: 30rpx;" v-for="(item,index) in getval" :key="index">
<u-icon name="clock-fill" color="#ccc" size="25"></u-icon>
<text class="tory1">{{item}}</text>
</view>
</view>
</view>
.x{
margin: 50rpx auto;
width: 90%;
height:600rpx;
box-shadow: 0 3px 7px #ccc;
.show{
display: flex;
justify-content: space-between;
padding: 20rpx;
}
.tory1 {
margin-left: 20rpx;
}
}
js部分
data() {
return {
setval: '',
getval: [],
}
},
onLoad() {
uni.getStorageSync('token')
let getval = uni.getStorageSync('token')
console.log('1111', getval); // ['苹果']
if (getval) {
this.getval = JSON.parse(getval)
}
},
methods: {
Storage() {
if (!this.setval) return; // 判断一下输入框是否有内容
let searchval = this.setval
// 使用findindex方法查询一下本地数据中是否有与输入内容重复的
let syncval = this.getval.findIndex(item => item == this.setval)
if(syncval>-1){
this.getval.splice(syncval)
// 此时添加成功了,但是本地中显示为空数组
}
// 所以需要在指定位置添加数据
this.getval.unshift(this.setval)
// 将输入框的数据转化为字符串后存入
uni.setStorageSync('token', JSON.stringify(this.getval))
},
// 清空按钮
historeDelete(){
const that=this
uni.showModal({
title:"温馨提示",
content:"是否确认清空",
success(res){
if(res.confirm){
that.getval=[]
uni.removeStorageSync('token')
}
}
})
}
}
}
效果: