微信小程序(原生)搜索功能实现

 一、效果图

微信小程序(原生)搜索功能实现_第1张图片

 二、代码

wxml


 搜索



	
		搜索历史
		
			
			清空历史
		
	
	
		{{item}}
	



	一共搜索出{{total}}产品



	
		
		11
	


scss

.history{
	padding: 30rpx;
	.title{
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-size: 30rpx;
		color: #666;
		.text{
			font-size: 32rpx;
		}
		.remove{
			color: #999;
			display: flex;
			align-items: center;
			.font{
				padding-left: 5rpx;
			}
		}
	}
	.content{
		padding: 20rpx 0;
		display: flex;
		flex-wrap: wrap;
		.item{
			color: #333;
			background-color: aqua;
			border-radius: 20rpx;
			font-size: 25rpx;
			padding: 8rpx 25rpx;
			margin: 0 20rpx 20rpx 0;
		}
	}
}
.total{
	padding: 30rpx;
	font-size: 28rpx;
	color: #666;
	.totalNum{
		color: red;
	}
}
.product_main{
	padding: 0 30rpx;
	display: flex;
	flex-wrap: wrap;
	justify-content: space-between;
	.main_item{
		margin-top: 20rpx;
		width: 320rpx;
		height: 200rpx;
		background-color: pink;
	}
}

js

import {
	queryProduct
} from '../../api/apis'
Page({
	data: {
		historyList: [], //搜索的历史记录
		productList: [], //搜到的产品
		total: 0,
		keyword: '',
		noData:false
	},
	onLoad(options) {
		let hisKey = wx.getStorageSync("hisKey") || null;
		if (hisKey) {
			this.setData({
				historyList: hisKey
			})
		}
	},
	hisItemClick(item) {
		this.setData({
			keyword: item.currentTarget.dataset.value
		})
		this.getSearchData()
	},
	onClear() {
		this.setData({
			keyword: '',
			productList: [],
			total: 0,
			noData:false
		})
	},
	onChange(e) {
		this.setData({
			keyword: e.detail
		})
	},
	// 确认搜索
	onSearch() {
		if (this.data.keyword.trim().length == '') {
			wx.showToast({
				title: '请输入搜索内容',
				icon: 'none',
			})
			return
		}
		console.log('123');
		let hisArr = this.data.historyList || []
		hisArr.unshift(this.data.keyword)
		hisArr = [...new Set(hisArr)]
		hisArr = hisArr.slice(0, 5)
		this.setData({
			historyList: hisArr
		})
		wx.setStorageSync("hisKey", hisArr)
		this.getSearchData()
	},
	// 获取搜索到的数据
	getSearchData() {
		queryProduct({
			keyword: this.data.keyword,
			limit: 10
		}).then(res => {
			console.log(res);
			let noData = false
			if(res.data.length == 0) {
				noData=true
			}
			this.setData({
				total: res.total,
				productList: res.data,
				noData
			})
		})
	},
	handleHistoryRemove() {
		wx.showModal({
		  title: '提示',
		  content: '是否确定清空历史?',
		  success: (res)=> {
		    if (res.confirm) {
		      this.setData({
		      	historyList: [],
		      	productList: [], 
		      	total: 0,
		      	keyword: '',
		      	noData:false
		      })
		      wx.removeStorageSync('hisKey')
		    } else if (res.cancel) {
		      console.log('用户点击取消')
		    }
		  }
		})
	
	},
})

json文件是引入的vant

{
  "usingComponents": {
    "van-search": "@vant/weapp/search/index",
	 "van-empty": "@vant/weapp/empty/index"
  }
}

你可能感兴趣的:(微信小程序,小程序)