先来看页面效果:
要求实现的效果:
1.页面由搜索栏+最近搜索+热门搜索组成;
2.当没有搜索结果时要进行必要的提示;
3.最近搜索展示用户的搜索历史,用户输入的搜索条件添加到最近搜索清单中,刷新页面的时候搜索历史保留,可对搜索历史进行删除;
4.当用户点击最近搜索或热闹搜索某一项时,该项填充到搜索栏中。
要想实现上面的效果,需要先安装2个插件:uni-search-bar 和uv-empty
uni-search-bar为uniapp官方扩展组件,可到这里进行了解更多信息并进行下载安装使用:
而uv-empty插件则实现搜索结果为空的样式,需要到DCloud 插件市场下载uv-empty 内容为空 全面兼容vue3+2、app、h5、小程序等多端 - DCloud 插件市场
下面是实现过程:
模板代码:
<template>
<view class="searchLayout">
<view class="search">
<uni-search-bar
@confirm="onSearch"
@cancel="onClear"
@clear="onClear"
focus
placeholder="搜索"
v-model="queryParams.keyword">
</uni-search-bar>
</view>
<view>
<view class="history" v-if="historySearch.length">
<view class="topTitle">
<view class="text">最近搜索</view>
<view class="icon" @click="removeHistory">
<uni-icons type="trash" size="25"></uni-icons>
</view>
</view>
<view class="tabs">
<view class="tab" v-for="tab in historySearch" :key="tab" @click="clickTab(tab)">{{tab}}</view>
</view>
</view>
<view class="recommend">
<view class="topTitle">
<view class="text">热门搜索</view>
</view>
<view class="tabs">
<view class="tab" v-for="tab in recommendList" :key="tab" @click="clickTab(tab)">{{tab}}</view>
</view>
</view>
</view>
<view class="noSearch">
<uv-empty mode="search" icon="http://cdn.uviewui.com/uview/empty/search.png"></uv-empty>
</view>
<view>
<view class="list">
<navigator :url="`/pages/preview/preview`" class="item"
v-for="item in classList" :key="item._id">
<image :src="item.smallPicurl" mode="aspectFill"></image>
</navigator>
</view>
<view v-if="noData || classList.length"><uni-load-more :status="noData?'noMore':'loading'"/></view>
</view>
</view>
</template>
JS代码:
<script setup>
import {ref} from "vue";
import {onLoad,onUnload,onReachBottom} from "@dcloudio/uni-app";
//查询参数
const queryParams = ref({
pageNum:1,
pageSize:12,
keyword:""
})
//搜索历史词,从缓存中读取,读取不到则赋值为空数组
const historySearch = ref(uni.getStorageSync("historySearch")|| []);
//热门搜索词
const recommendList = ref(["美女","帅哥","宠物","卡通"]);
//没有更多
const noData = ref(false);
//没有搜索结果
const noSearch = ref(false);
//搜索结果列表
const classList = ref([
{_id:123123,smallPicurl:'https://mp-0cb878b7-99ec-44ea-8246-12b123304b05.cdn.bspapp.com/xxmBizhi/20231102/1698905562410_0_small.webp'}
]);
//点击搜索,将当前搜索的关键字追加到历史搜索数组中并进行去重
const onSearch = ()=>{
historySearch.value =[...new Set([queryParams.value.keyword,...historySearch.value])]
// 将当前搜索的关键字保存到缓存中
uni.setStorageSync("historySearch",historySearch.value)
}
//点击清除按钮
const onClear = ()=>{
}
//点击标签进行搜索,将标签的值赋给搜索关键字
const clickTab = (value)=>{
queryParams.value.keyword = value
}
//点击清空搜索记录,清空时需要将缓存和搜索历史数组同时清空
const removeHistory = ()=>{
uni.showModal({
title:"是否清空历史搜索?",
success:res=>{
if(res.confirm){
uni.removeStorageSync("historySearch");
historySearch.value = []
}
}
})
}
//触底加载更多
onReachBottom(()=>{
})
//关闭有页面
onUnload(()=>{
})
</script>