搜索历史功能实现,同时持久化存储,重复搜索去重并置顶,以及清除搜索历史,uniapp原生导航栏

 

<template>
	<view>
		<view class="search">
			<view class="title">
				<view>最近搜索</view>
				<text class="iconfont icon-lajitong" @click="clear"></text>
			</view>
			<view>
				<view class="name" 
				v-for='(item,index) in searchList' :key="index"
				>{{item}}</view>
			</view>
		</view>
	</view>
</template>

<script> 
	export default {
		data() {
			return {
				keyword:'',
				searchList:[]
			}
		},
		// 监听点击搜索
		onNavigationBarButtonTap(e) {
			this.search()
		},
		// 获取搜索框value
		onNavigationBarSearchInputChanged(e) {
			this.keyword = e.text
		},
		// 软键盘搜索
		onNavigationBarSearchInputConfirmed() {
			this.search()
		},
		// 读取搜索历史
		mounted() {
			uni.getStorage({
				key: 'search',
				success: (res)=>{
					this.searchList = JSON.parse(res.data) 
				}
			})
		},
		methods: {
			// 搜索框判断不能为空
			search(){
				if (this.keyword =='') {
					return uni.showToast({
						title:'关键词不能为空',
						icon:'none'
					})
				}
				// 收起软键盘
				uni.hideKeyboard();
				this.addSearch();
			},
			// 存储搜索历史
			addSearch(){
				this.searchList.unshift(this.keyword);  //搜索的历史置顶
				this.searchList = Array.from(new Set(this.searchList))  //去重
				uni.setStorage({
					key:'search',
					data: JSON.stringify(this.searchList),
				})
			},
			// 清除搜索历史
			clear(){
				uni.removeStorage({
					key: 'search',
				});
				// 更新dom
			   uni.redirectTo({
				   url: '/pages/search/search'
			   });
			}
		}
	}
</script>

<style scoped lang="scss">
	.search{
		display: flex;
		flex-direction: column;
		padding: 20rpx;
		.title{
			display: flex;
			justify-content: space-between;
			text{
				font-size: 40rpx;
			}
		}
		.name{
			display: inline-block;
			background: #f1f1f1;
			color: #282828;
			border-radius: 30rpx;
			padding: 10rpx 20rpx;
			font-size: 28rpx;
			margin: 10rpx;
		}
	}
</style>

原生导航栏配置

        {
	        "path" : "pages/search/search",
	        "style" :                                                                                    
	        {
	            "enablePullDownRefresh": false,
	    		"navigationBarBackgroundColor": "#FFFFFF",
	    		"app-plus": {
	    			"scrollIndicator": "none",
	    			"titleNView": {
	    				"searchInput": {
	    					"align": "left",
	    					"placeholder": "搜索",
	    					"disabled": false,
	    					"autoFocus": true,
	    					"borderRadius": "15px",
	    					"backgroundColor": "#F7F7F7",
	    					"placeholderColor": "#B3B3B3"
	    				},
	    				"buttons": [
	    					{
	    						"float": "right",
	    						"color": "#636363",
	    						"text": "搜索",
	    						"fontSize": "16px",
	    						"width":"40px"
	    					}
	    				]
	    			}
	    		}
	        }
	        
	    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值