Files
zgty-mas-m/pages/index/search.vue
2025-09-30 00:08:23 +08:00

144 lines
3.5 KiB
Vue

<!-- 搜索界面 -->
<template>
<s-layout :bgStyle="{ color: '#FFF' }" class="set-wrap" title="搜索">
<view class="search-container">
<view class="search-input-wrapper">
<u-search
v-model="searchText"
placeholder="请输入关键字"
:show-action="false"
:focus="true"
shape="square"
@search="onSearch"
@confirm="onSearch"
/>
</view>
<!-- 搜索历史标题 -->
<view class="search-section">
<view class="section-header">
<u-text text="搜索历史" size="16" bold color="#333" />
<u-button
text="清除搜索历史"
size="mini"
type="error"
plain
@click="onDelete"
/>
</view>
<!-- 历史标签 -->
<view class="history-tags" v-if="state.historyList.length">
<u-tag
v-for="(item, index) in state.historyList"
:key="index"
:text="item"
type="info"
plain
size="medium"
closable
@click="onSearch(item)"
@close="removeHistoryItem(index)"
:custom-style="{ margin: '5rpx 10rpx 5rpx 0' }"
/>
</view>
<!-- 无历史提示 -->
<u-empty
v-else
mode="search"
text="暂无搜索历史"
textSize="14"
/>
</view>
</view>
</s-layout>
</template>
<script setup>
import { reactive, ref } from 'vue';
import sheep from '@/sheep';
import { onLoad } from '@dcloudio/uni-app';
const searchText = ref('');
const state = reactive({
historyList: [],
});
// 搜索
function onSearch(keyword = '') {
const searchKeyword = keyword || searchText.value;
if (!searchKeyword) {
return;
}
saveSearchHistory(searchKeyword);
// 前往商品列表(带搜索条件)
sheep.$router.go('/pages/goods/list', { keyword: searchKeyword });
}
// 移除单个历史记录
function removeHistoryItem(index) {
state.historyList.splice(index, 1);
uni.setStorageSync('searchHistory', state.historyList);
}
// 保存搜索历史
function saveSearchHistory(keyword) {
// 如果关键词在搜索历史中,则把此关键词先移除
if (state.historyList.includes(keyword)) {
state.historyList.splice(state.historyList.indexOf(keyword), 1);
}
// 置顶关键词
state.historyList.unshift(keyword);
// 最多保留 10 条记录
if (state.historyList.length >= 10) {
state.historyList.length = 10;
}
uni.setStorageSync('searchHistory', state.historyList);
}
function onDelete() {
uni.$u.modal({
title: '提示',
content: '确认清除搜索历史吗?',
showCancelButton: true,
confirmText: '确定',
cancelText: '取消'
}).then(res => {
if (res) {
state.historyList = [];
uni.removeStorageSync('searchHistory');
}
});
}
onLoad(() => {
state.historyList = uni.getStorageSync('searchHistory') || [];
});
</script>
<style lang="scss" scoped>
.search-container {
padding: 30rpx;
}
.search-input-wrapper {
margin-bottom: 40rpx;
}
.search-section {
.section-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 20rpx;
}
.history-tags {
display: flex;
flex-wrap: wrap;
align-items: flex-start;
}
}
</style>