food_wechat/pages/shop/search.vue

97 lines
2.8 KiB
Vue
Raw Normal View History

<template>
<view class="vh100 flex column">
<!-- topbar -->
<u-navbar title="搜索商品" bgColor="#d43030" :titleStyle="{ color: '#FFF'}" :autoBack="true" placeholder>
<view class="u-nav-slot" slot="left">
<u-icon name="arrow-left" color="#fff" size="19"></u-icon>
</view>
</u-navbar>
<!-- 搜索框 -->
<view class="search-container flex mac m-l-24 m-r-24">
<input class="borderno rad16 m-r-12 bg-w fz28 p-12 flex1" v-model="searchQuery" placeholder="请输入商品名称"
@input="handleSearch" />
<u-icon name="search" color="#d43030" size="32" @click="handleSearch"></u-icon>
</view>
<!-- 搜索结果展示 -->
<view class="m-l-24 m-r-24 flex1 ofa">
<view v-if="filteredSpuList.length > 0">
<listItem v-for="spuItem in filteredSpuList" :key="spuItem.id" :spu="spuItem" />
</view>
<template v-else>
<u-divider v-if="searchQuery" text="没有找到相关商品" :hairline="true"></u-divider>
</template>
<!-- 底部空白占位 -->
<view class="extra-space2"></view>
</view>
<!-- 购物车按钮 -->
<cartBut></cartBut>
<!-- 购物车折叠层 -->
<cartFold></cartFold>
</view>
</template>
<script>
export default {
data() {
return {
searchQuery: '', // 绑定搜索框的输入内容
filteredSpuList: [], // 存储过滤后的spu列表
}
},
computed: {
// spuList 直接从 Vuex 获取
spuList() {
return this.$store.state.spuList
}
},
watch: {
// 监听 spuList 的变化,初始化过滤
spuList(newSpuList) {
this.filteredSpuList = this.filterSpuList(this.searchQuery, newSpuList)
},
// 监听 searchQuery实时更新过滤结果
searchQuery(newQuery) {
this.filteredSpuList = this.filterSpuList(newQuery, this.spuList)
}
},
methods: {
// 搜索处理方法
handleSearch() {
if (this.searchQuery.trim() === '') {
this.filteredSpuList = [] // 如果搜索框为空,清空结果
} else {
this.filteredSpuList = this.filterSpuList(this.searchQuery, this.spuList) // 执行过滤
}
},
// 过滤 spuList
filterSpuList(query, spuList) {
if (!query.trim()) return [] // 如果没有输入关键词,返回所有商品
const lowerQuery = query.toLowerCase()
return spuList.filter(spuItem => {
// 过滤 name 字段
const nameMatch = spuItem.name.toLowerCase().includes(lowerQuery)
// 过滤 pro_tag 数组
const tagMatch = spuItem.pro_tag.some(tag => tag.toLowerCase().includes(lowerQuery))
// 过滤 bind_sku 中的 name 字段
const skuMatch = spuItem.bind_sku.some(sku => sku.tit.toLowerCase().includes(lowerQuery))
// 如果 name、pro_tag 或 bind_sku 匹配,返回该 spu
return nameMatch || tagMatch || skuMatch
})
}
}
}
</script>
<style scoped>
.search-container {
height: 100rpx;
}
</style>