作者:颂春堂中药 | 来源:互联网 | 2023-09-11 17:45
本文主要基于微信小程序实现和uni-app实现搜索商品和历史记录的功能。 不详细介绍,主看代码注释即可!!
1、搜索组件页面代码块
<template><view><!-- uni的搜索框 --><view class="search-box"><uni-search-bar @input="input" :radius="100" cancelButton="none"></uni-search-bar></view><!-- 搜索建议列表 --><view class="sugg-list" v-if="searchResults.length !== 0"><view class="sugg-item" v-for="(item,i) in searchResults" :key="i" @click="gotoDatail(item)"><view class="goos-name"> {{item.goods_name}} </view><uni-icons type="arrowright" size="17" ></uni-icons></view></view><!-- 搜索历史盒子 --><view class="history-box" v-else><!-- 历史标题区域 --><view class="history-title"><text>搜索历史</text><uni-icons type="trash" size="17" @click="cleanHistory"></uni-icons></view><!-- 历史记录列表区域 --><view class="history-list"><uni-tag :text="item" v-for="(item,i) in historyList" :key="i"></uni-tag></view></view></view>
</template>
页面实现效果图如下图:
2、样式代码块
<style lang="scss">.search-box {position: sticky; top: 0;z-index: 999;.uni-searchbar {background-color: #C00000 !important;}}
.sugg-list {padding: 0 5px;.sugg-item {display: flex;align-items: center;justify-content: space-between; font-size: 12px;padding: 13px 0;border-bottom: 1px solid #EEEEEE;.goos-name {white-space: nowrap; overflow: hidden;text-overflow: ellipsis; }}}
.history-box {padding: 0 5px;.history-title {display: flex;justify-content: space-between; height: 40px;align-items: center;font-size: 13px;border: 1px solid #efefef;.history-list {display: flex;flex-wrap: wrap;.uni-tag {margin: 0 2px;}}}}
</style>
3、逻辑代码块
<script>export default {data() {return {timer: null, kw: &#39;&#39;, searchResults: [], historyList: [], };},onLoad() { this.historyList = JSON.parse(uni.getStorageSync(&#39;kw&#39;) || &#39;[]&#39;) },methods: {input(e) { clearTimeout(this.timer) this.timer = setTimeout(() => { this.kw = e this.getSearchList() }, 500)},async getSearchList() {if (this.kw.length === 0) {this.searchResults = [] return }const {data: res} = await uni.$http.get(&#39;/api/.....&#39;, {query: this.kw})if (res.meta.status !== 200) return uni.$showMsg()this.searchResults = res.messagethis.saveSearchHistory() },gotoDatail(item) {uni.navigateTo({url: &#39;/subpkg/goods_detail/goods_detail?goods_id=&#39; + item.goods_id})},saveSearchHistory() { const index = this.historyList.findIndex(x => x === this.kw) if (index >= 0) {this.historyList.splice(index, 1)}this.historyList.unshift(this.kw)uni.setStorageSync(&#39;kw&#39;, this.historyList)},cleanHistory() { this.historyList = []uni.setStorageSync(&#39;kw&#39;, &#39;[]&#39;)}}}
</script>
以上就是实现小程序搜索功能,历史记录功能的实现,当然这也是一种实现思路方法,没有完全正确的。