// pages/search/index.js Page({ data: { keyword: '', searchHistory: [], hotSearches: [ 'iPhone 14 Pro Max', '华为 Mate60 Pro', '小米14 Pro', 'MacBook Pro', 'iPad Pro', 'Apple Watch', 'AirPods Pro', 'Switch OLED' ], suggestions: [] }, onLoad() { // 获取搜索历史 const history = wx.getStorageSync('searchHistory') || [] this.setData({ searchHistory: history }) }, // 输入关键词 onInput(e) { const keyword = e.detail.value.trim() this.setData({ keyword }) if (keyword) { this.getSuggestions(keyword) } else { this.setData({ suggestions: [] }) } }, // 获取搜索建议 getSuggestions(keyword) { // 模拟搜索建议 const suggestions = this.data.hotSearches.filter(item => item.toLowerCase().includes(keyword.toLowerCase()) ) this.setData({ suggestions }) }, // 执行搜索 onSearch(e) { const keyword = (e.detail?.value || this.data.keyword).trim() if (!keyword) return this.saveSearchHistory(keyword) this.navigateToResult(keyword) }, // 点击标签搜索 onTagClick(e) { const { keyword } = e.currentTarget.dataset this.setData({ keyword }) this.saveSearchHistory(keyword) this.navigateToResult(keyword) }, // 保存搜索历史 saveSearchHistory(keyword) { let history = this.data.searchHistory // 移除已存在的相同关键词 history = history.filter(item => item !== keyword) // 将新关键词添加到开头 history.unshift(keyword) // 只保留最近10条 history = history.slice(0, 10) this.setData({ searchHistory: history }) wx.setStorageSync('searchHistory', history) }, // 清空搜索历史 clearHistory() { wx.showModal({ title: '提示', content: '确定要清空搜索历史吗?', success: (res) => { if (res.confirm) { this.setData({ searchHistory: [] }) wx.removeStorageSync('searchHistory') } } }) }, // 清除关键词 clearKeyword() { this.setData({ keyword: '', suggestions: [] }) }, // 取消搜索 onCancel() { wx.navigateBack() }, // 跳转到搜索结果页 navigateToResult(keyword) { wx.navigateTo({ url: `/pages/search/result?keyword=${encodeURIComponent(keyword)}` }) } })