uni-app之旅-day03-搜索

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


5. 搜索

提示:以下是本篇文章正文内容,下面案例可供参考

5.0 创建 search 分支

git checkout -b search

5.1 自定义搜索组件

  • 🍔🍔🍔5.1.1 自定义 my-search 组件
  • 在项目根目录的 components 目录上,鼠标右键,选择 新建组件
  • 在分类cate.vue页面的 UI 结构中,直接以标签的形式使用 my-search 自定义组件
<!-- 使用自定义的搜索组件 -->
<my-search></my-search>
<view class="scroll-view-container">
<!-- 左侧滚动视图区域 -->
</view>
  • 定义 my-search 组件的 UI 结构
<view class="my-search-container">
		<!-- 使用 view 组件模拟 input 输入框的样式 -->
		<view class="my-search-box">
			<uni-icon type="search" size="17"></uni-icon>
			<text class="placeholder">搜索</text>
		</view>
	</view>
  • 注意:在当前组件中,我们使用 view 组件模拟 input 输入框的效果;并不会在页面上渲染真正的 input 输入框
.my-search-container{
	background-color: #c00000;
	height: 50px;
	padding: 0 10px;
	display: flex;
	align-items: center;
}
.my-search-box{
	height: 36px;
	background-color: #ffffff;
	border-radius: 15px;
	width: 100%;
	display: flex;
	align-items: center;
	justify-content: center;
	.placeholder{
		font-size: 15px;
		margin-left: 5px;
	}
}
  • 由于自定义的 my-search 组件高度为 50px,因此,需要重新计算cate.vue分类页面窗口的可用高度
onLoad(){
	this.wh = sysInfo.windowHeight - 50;
}

5.1.2 my-search.vue组件通过自定义属性增强组件的通用性

  • 🚜🚜🚜为了增强组件的通用性,我们允许使用者自定义搜索组件的 背景颜色 和 圆角尺寸
  • 通过 props 定义 bgcolor 和 radius 两个属性,并指定值类型和属性默认值:
props:{
	//背景颜色
			bgcolor:{
				type:String,
				default:'#C00000'
			},
			//圆角尺寸
			radius:{
				type:Number,
				default:18
			}
}
  • 通过属性绑定的形式,为 .my-search-container 盒子和 .my-search-box 盒子动态绑定 style 属性
<view class="my-search-container" :style="{'background-color':bgcolor}">
		<!-- 使用 view 组件模拟 input 输入框的样式 -->
		<view class="my-search-box" :style="{'border-radius':radius + 'px'}" @click="searchBoxHandler">
			<uni-icon type="search" size="17"></uni-icon>
			<text class="placeholder">搜索</text>
		</view>
	</view>
  • 移除对应 scss 样式中的 背景颜色 和 圆角尺寸
.my-search-container {
  // 移除背景颜色,改由 props 属性控制
  // background-color: #C00000;
  height: 50px;
  padding: 0 10px;
  display: flex;
  align-items: center;
}

.my-search-box {
  height: 36px;
  background-color: #ffffff;
  // 移除圆角尺寸,改由 props 属性控制
  // border-radius: 15px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;

  .placeholder {
    font-size: 15px;
    margin-left: 5px;
  }
}

5.1.3 为自定义组件封装 click 事件

  • 🌮🌮🌮在 my-search 自定义组件内部,给类名为 .my-search-box 的 view 绑定 click 事件处理函数
<view class="my-search-box" :style="{'border-radius': radius + 'px'}" @click="searchBoxHandler">
  <uni-icons type="search" size="17"></uni-icons>
  <text class="placeholder">搜索</text>
</view>
  • 在 my-search 自定义组件的 methods 节点中,声明事件处理函数
methods:{
	searchBoxHandler(){
		// 触发外界通过 @click 绑定的 click 自定义事件处理函数
		 this.$emit('click')
	}
}
  • 在分类页面中使用 my-search 自定义组件时,即可通过 @click 为其绑定点击事件处理函数
<!-- 使用自定义的搜索组件 -->
<my-search @click="gotoSearch"></my-search>
methods:{
	//跳转到分包中的搜索页面
	gotoSearch(){
		uni.navigateTo({
			url:'/subpkg/search/search'
		})
	}
}

5.2 搜索建议

5.2.1 渲染搜索页面的基本结构

  • 🍕🍕🍕定义如下的 UI 结构
<view class="search-box">
  <!-- 使用 uni-ui 提供的搜索组件 -->
  <uni-search-bar @input="input" :radius="100" cancelButton="none"></uni-search-bar>
</view>
  • 修改 components -> uni-search-bar -> uni-search-bar.vue 组件,将默认的白色搜索背景改为 #C00000 的红色背景
.uni-searchbar {
  /* #ifndef APP-NVUE */
  display: flex;
  /* #endif */
  flex-direction: row;
  position: relative;
  padding: 16rpx;
  /* 将默认的 #FFFFFF 改为 #C00000 */
  background-color: #c00000;
}
  • 实现搜索框的吸顶效果
.search-box {
  position: sticky;
  top: 0;
  z-index: 999;
}
  • 定义如下的 input 事件处理函数
methods:{
	input(e){
		 //e 是最新搜索内容
		console.log(e)
	}
}

5.2.2 实现搜索框自动获取焦点

  • 🥞🥞🥞修改 components -> uni-search-bar -> uni-search-bar.vue 组件,把 data 数据中的 show 和 showSync 的值,从默认的 false 改为 true 即可
  • 使用手机扫码预览,即可在真机上查看效果

5.2.3 实现搜索框的防抖处理

  • 在search.vue组件 data 中定义防抖的延时器 timer 如下
data() {
  return {
    // 延时器的 timer
    timer: null,
    // 搜索关键词
    kw: ''
  }
}
  • 修改 input 事件处理函数
methods:{
	input(e){
		clearTimeout(this.timer)
		this.timer = setTimeout(()=>{
			this.kw = e;//是搜索的值
			console.log(this.kw) 
		},500) 
	}
}

5.2.4 根据关键词查询搜索建议列表

  • 🍔🥟🍔在 data 中定义如下的数据节点,用来存放搜索建议的列表数据
data(){
	return{
	 // 延时器的 timerId
		timer: null,
	// 存储搜索关键字
		kw:'',
		//存储搜索结果列表
		searchResults:[] 
	}
}
  • 在防抖的 setTimeout 中,调用 getSearchList 方法获取搜索建议列表
this.timer = setTimeout(()=>{
					// 如果 500 毫秒内,没有触发新的输入事件,则为搜索关键词赋值
					this.kw = e
					//根据关键字,查询搜索建议列表
					this.getSearchList()
					console.log(this.kw)
				},500)
  • 在 methods 中定义 getSearchList 方法
//根据关键字,搜索商品建议列表
			async getSearchList() {
				//判断关键字是否为空
				if (this.kw === '') {
					this.searchResults = []
					return
				}
				//获取列表数据,发请求
				const {
					data: res
				} = await uni.$http.get('/api/public/v1/goods/qsearch', {
					query: this.kw
				})
				console.log(res)
				if (res.meta.status !== 200) return uni.$showMsg()
				this.searchResults = res.message;
			}

定义如下的 UI 结构

<!-- 搜索建议列表 -->
		<view class="sugg-list">
			<view class="sugg-item" v-for="(item,i) in searchResults" :key="i" @click="gotoDetail(item.goods_id)">
				<view class="goods-name">
					{{ item.goods_name }}
				</view>
				<uni-icons type="arrowright" size="16"></uni-icons>
			</view>
		</view>
  • 美化搜索建议列表
.sugg-list{
		padding: 0 5px;
		.sugg-item{
			font-size: 12px;
			padding: 13px 0;
			border-bottom: 1px solid #efefef;
			display: flex;
			align-items: center;
			justify-content: space-between;
			.goods-name{
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
				margin-right: 3px;
			}
		}
	}
  • 点击搜索建议的 Item 项,跳转到商品详情页面
gotoDetail(goods_id){
				uni.navigateTo({
					//指定详情页面的url地址,并传递参数
					url:'/subpkg/goods_detail/goods_detail?goods_id=' + goods_id
				})
			}

5.3 搜索历史

5.3.1 渲染搜索历史记录的基本结构

  • 🍔🍔🍔在 data 中定义搜索历史的初始数据
historyList:['a','app','apple']
  • 渲染搜索历史区域的 UI 结构
<!-- 搜索建议列表 -->
<view></view>
<!-- 历史记录 -->
		<view class="history-box" v-else>
			<!-- 标题区域 -->
			<view class="history-title">
				<text>搜索历史</text>
				<uni-icons type="trash" size="17"></uni-icons>
			</view>
			<!-- 列表区域 -->
			<view class="history-list">
				<uni-tag :text="item" v-for="(item,i) in historyList" :key="i"></uni-tag>
			</view>
		</view>
  • 🥟🥟🥟搜索历史区域的样式
.history-box {
  padding: 0 5px;

  .history-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 40px;
    font-size: 13px;
    border-bottom: 1px solid #efefef;
  }

  .history-list {
    display: flex;
    flex-wrap: wrap;

    .uni-tag {
      margin-top: 5px;
      margin-right: 5px;
    }
  }
}

5.3.2 实现搜索建议和搜索历史的按需展示

  • 🥞🍕🥞根据搜索结果列表的长度不为 0的时候(searchResults.length !== 0),需要展示搜索建议区域,隐藏搜索历史区域
  • 当搜索结果列表的长度等于 0的时候(searchResults.length === 0),需要隐藏搜索建议区域,展示搜索历史区域
  • 使用 v-if 和 v-else 控制这两个区域的显示和隐藏
<!-- 搜索建议列表 -->
<view class="sugg-list" v-if="searchResults.length !== 0">
  <!-- 省略其它代码... -->
</view>

<!-- 搜索历史 -->
<view class="history-box" v-else>
  <!-- 省略其它代码... -->
</view>

5.3.3 将搜索关键词存入 historyList

methods:{
	async getSearchList(){
		 //省略其它代码... 
		this.saveSearchHistory() 
	},
	saveSearchHistory(){
		this.historyList.push(this.kw) 
	}
},

5.3.4 解决关键字前后顺序的问题

  • 🍔🌮🍔定义一个计算属性 historys,将 historyList 数组 reverse 反转之后,就是此计算属性的值
computed:{
	historys(){
		return [...this.historyList].reverse() 
	}
}
  • 页面中渲染搜索关键词的时候,不再使用 data 中的 historyList,而是使用计算属性 historys
<uni-tag :text="item" v-for="(item,i) in historyList" :key="i"></uni-tag>

5.3.5 解决关键词重复的问题和将搜索历史记录持久化存储到本地

saveSearchHistory(){
	// this.historyList.push(this.kw)
	// 借助Set数据结构去重 转换为Set
	const set = new Set(this.historyList)
	set.delete(this.kw)
	set.add(this.kw)
	this.historyList = Array.from(set)
	//调用uni提供的setStorageSync(key,val) 将搜索历史记录持久化存储到本地
	uni.setStorageSync('kw',JSON.stringify(this.historyList))
}
  • 在 onLoad 生命周期函数中,加载本地存储的搜索历史记录
onLoad(){
	this.historyList = JSON.parse(uni.getStorageSync('kw') || '[]')
}

5.3.7 清空搜索历史记录

  • 🚜🚜🚜为清空的图标按钮绑定 click 事件
<text>搜索历史</text>
				<uni-icons type="trash" size="17" @click="cleanHistory"></uni-icons>
  • 在 methods 中定义 cleanHistory 处理函数
//清空搜索记录
cleanHistory(){
	this.historyList = [];
	uni.setStorageSync('kw','[]')
}

5.3.8 点击搜索历史跳转到商品列表页面

  • 🍕🍕🍕为搜索历史的 Item 项绑定 click 事件处理函数
<!-- 列表区域 -->
			<view class="history-list">
				<uni-tag :text="item" v-for="(item,i) in historys" :key="i" @click="gotoGoodsList(item)"></uni-tag>
			</view>
  • 定义 gotoGoodsList 处理函数
//点击搜索历史跳转到商品列表页面
gotoGoodsList(kw){
	uni.navigateTo({
		url:'/subpkg/goods_list/goods_list?query=' + kw 
	})
}

5.4 分支的合并与提交

  • 退回到项目根目录,打开cmd命令窗口

  • 1.将search分支进行本地提交
    – git add .
    – git commit -m ‘’

  • 2.将本地的 search 分支推送到码云
    –git push -u origin search

  • 将本地 search 分支中的代码合并到 master 分支
    –git checkout master
    –git merge search

  • 3.将本地master推送到码云
    –git push

  • 4.删除本地search分支
    –git branch -d search

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值