uniapp | 搜索页 显示或清除历史记录 | 代码分析

一、主要功能和演示

1.搜索页的主要功能

(1)输入关键词,点击搜索(或键盘回车),页面跳转到搜索结果页
(2)之前搜索过的关键词在历史记录里显示,并且按最近到最远搜索过的顺序排列
(即:若搜索一个关键词时,此关键词在之前已在历史记录里(非第一位),那么本次搜索过后,此关键词会在历史记录里列第一位,之前的位置取消)
(3)点击“清除全部”后,历史记录全部清除

2.搜索页演示


在这里插入图片描述

二、用到的uniapp相关函数

1.uniapp支持如下 页面生命周期函数:

官网相关内容的链接

函数名 说明
onLoad 监听页面加载,其参数为上个页面传递的数据,参数类型为 Object(用于页面传参)
onNavigationBarButtonTap 监听原生标题栏按钮点击事件,参数为Object
onNavigationBarSearchInputChanged 监听原生标题栏搜索输入框输入内容变化事件
onNavigationBarSearchInputConfirmed 监听原生标题栏搜索输入框搜索事件,用户点击软键盘上的“搜索”按钮时触发

2.uniapp数据缓存

官网相关内容的链接

函数名 说明
uni.setStorageSync(KEY,DATA) 将 data 存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个同步接口
uni.getStorageSync(KEY) 从本地缓存中同步获取指定 key 对应的内容
uni.removeStorageSync(KEY) 从本地缓存中同步移除指定 key

三、代码分析

重要函数

(1)添加历史记录并更新顺序addHistory()

addHistory(searchValue){
    
    
  if(!searchValue){
    
     return this.$toast('请输入关键词')
  //查找searchValue是否在历史记录的list里
  //获取searchValue在历史记录list里的index
  const findItem = this.list.findIndex(item => item == searchValue)
  //若searchValue在历史记录list里,且searchValue不在list的第一位
  if (findItem !== -1 && findItem !== 0) {
    
    
    //删除历史记录list里的曾经的同值searchValue
    this.list.splic(findItem,1)
    //unshift在list开头插入searchValue
    this.list.unshift(searchValue)
  } else {
    
    
    this.list.unshift(searchValue)
  }
  
  //将更新后的list存储在本地缓存中指定的'searchHistory'中
  uni.setStorageSync('searchHistroy', JSON.stringify(this.list))
  //页面跳转至搜索结果页
  this.$navigateTo(`/pages/search-result/search-result?value=${
      
      searchValue}`)
}

(2)清除历史记录clearHistory()

clearHistory() {
    
    
  //显示模态弹窗,这里同时有确定和取消按钮,类似于一个API整合了html中:alert、confirm。
  uni.showModal({
    
    
    content:'是否清除历史记录',
    success: (res) => {
    
    
      //如果confirm,则清除历史记录的本地缓存并重新赋空值给list
      if(res.confirm) {
    
    
        uni.removeStorageSync('searchHistory')
        this.list = []
      } else if (res.cancel){
    
    
      
      }
    }
  });
}    

四、完整代码

1.search.vue 搜索页(含历史记录)

<template>
	<view>
		<view class="p-2 flex justify-between align-center">
			<text class="font-md font-weight-bold">历史记录</text>
			<text class="font-sm text-secondary" @click="clearHistory">清除全部</text>
		</view>
		<view class="flex flex-wrap p-2">
			<view v-for="(item,index) in list" :key="index" class="border font-sm mr-2 mb-2 p-2"
				style="border-radius: 4rpx;background-color: #f8f8f8;" @click="goResult(index)">{
    
    {
    
    item}}
			</view>
		</view>
	</view>
</template>

<script>
	export default {
    
    
		data() {
    
    
			return {
    
    
				list: [],
				searchValue: ''
			}
		},
		onNavigationBarSearchInputChanged(e) {
    
    
			this.searchValue = e.text
		},
		onNavigationBarButtonTap() {
    
    
			this.addHistory(this.searchValue)
		},
		onNavigationBarSearchInputConfirmed() {
    
    
			this.addHistory(this.searchValue)
		},
		onLoad() {
    
    
			const list = uni.getStorageSync('searchHistory')
			if (list) {
    
    
				this.list = JSON.parse(list)
			}
			console.log(this.list,'list');
		},
		methods: {
    
    
			goResult(index) {
    
    
				this.$navigateTo(`/pages/search-result/search-result?value=${
      
      this.list[index]}`)
			},
			addHistory(v) {
    
    
				if (!v) return this.$toast('请输入关键词')
				const findItem = this.list.findIndex(item => item === v)
				if (findItem !== -1 && findItem !== 0) {
    
    
					this.list.splice(findItem, 1)
					this.list.unshift(v)
				} else {
    
    
					this.list.unshift(v)
				}
				uni.setStorageSync('searchHistory', JSON.stringify(this.list))
				this.$navigateTo(`/pages/search-result/search-result?value=${
      
      v}`)
			},
			clearHistory() {
    
    
				uni.showModal({
    
    
					content: '是否确认清除历史记录',
					success: (res)=> {
    
    
						if (res.confirm) {
    
    
							uni.removeStorageSync('searchHistory')
							this.list =[]
						} else if (res.cancel) {
    
    
					
						}
					}
				});
			}
		}
	}
</script>
<style>
</style>

2.search-result.vue 搜索结果页

<template>
	<view class="result flex flex-column">
		<tabs :current="current" :tabs="tabs" @change="changeTab"></tabs>
		<!-- 搜索内容 -->
		<view class="flex-1">
			<swiper :current="current" :duration="1000" style="height: 100%;" @change="changeCurrent">
				<swiper-item v-for="(t,tIndex) in tabs" :key="tIndex">
					<scroll-view @scrolltolower="reachBottom" scroll-y="true" style="height: 100%;padding-top: 20rpx;">
						<course-list :item="item" v-for="(item,index) in t.list " :key="index" :type="t.type">
						</course-list>
						<!-- 加载loading -->
						<uni-load-more :status="t.loadStatus"></uni-load-more>
					</scroll-view>
				</swiper-item>
			</swiper>
		</view>
	</view>
</template>

<script>
	export default {
    
    
		data() {
    
    
			return {
    
    
				current: 0,
				tabs: [{
    
    
						name: '课程',
						loadStatus: 'more',
						type: 'one',
						list: [],
						page: 1
					},
					{
    
    
						name: '专题',
						loadStatus: 'more',
						type: 'two',
						list: [],
						page: 1
					}
				],
				limit: 10,
				list: [],
				searchValue: ''
			}
		},
		onNavigationBarSearchInputClicked() {
    
    
			uni.navigateBack()
		},
		onLoad(e) {
    
    
			this.searchValue = e.value
			this.getData()
		},
		methods: {
    
    
			getData() {
    
    
				const currentTab = this.tabs[this.current]
				const data = {
    
    
					keyword: this.searchValue,
					type: this.current == 0 ? 'course' : 'column',
					page: currentTab.page
				}
				currentTab.loadStatus = 'loading'
				this.$api.getSearchList(data).then(res => {
    
    
					console.log(res, 'res');
					currentTab.list = currentTab.page === 1 ? res.rows : [...currentTab.list, ...res.rows]
					if (res.rows.length < this.limit) {
    
    
						currentTab.loadStatus = 'noMore'
					} else if (res.rows.length === this.limit) {
    
    
						currentTab.loadStatus = 'more'
					}
				})
			},
			changeTab(e) {
    
    
				this.current = e
			},
			changeCurrent(e) {
    
    
				this.current = e.detail.current
				const currentTab = this.tabs[this.current]
				if (currentTab.loadStatus === 'more' && currentTab.page === 1) {
    
    
					this.getData()
				}
			},
			// 滚动底部事件
			reachBottom() {
    
    
				const currentTab = this.tabs[this.current]
				if (currentTab.loadStatus !== 'more') return
				currentTab.page++
				this.getData()
			}
		}
	}
</script>

<style scoped lang="less">
	page {
    
    
		height: 100%;

		.result {
    
    
			height: 100%;
		}
	}
</style>

猜你喜欢

转载自blog.csdn.net/qq_42376600/article/details/128769149