ertonglianxibiao/pages/search/search.js

161 lines
3.4 KiB
JavaScript
Raw Normal View History

2026-01-14 15:33:15 +08:00
import { injectPage } from '@jdmini/api'
const { searchWorksheets } = require('../../utils/api.js')
const { DATA_BASE_URL } = require('../../utils/config.js')
Page(injectPage({})({
data: {
dataBaseUrl: DATA_BASE_URL,
keyword: '',
history: [],
hotKeywords: ['字母', '数字', '涂色', '迷宫', '折纸', '形状'],
worksheets: [],
page: 1,
pageSize: 20,
total: 0,
hasMore: true,
loading: false,
hasSearched: false
},
onLoad() {
this.loadHistory()
},
// 加载搜索历史
loadHistory() {
try {
const history = wx.getStorageSync('searchHistory') || []
this.setData({ history })
} catch (error) {
console.error('加载搜索历史失败:', error)
}
},
// 保存搜索历史
saveHistory(keyword) {
try {
let history = wx.getStorageSync('searchHistory') || []
// 去重
history = history.filter(h => h !== keyword)
// 添加到开头
history.unshift(keyword)
// 最多保存10条
if (history.length > 10) {
history = history.slice(0, 10)
}
wx.setStorageSync('searchHistory', history)
this.setData({ history })
} catch (error) {
console.error('保存搜索历史失败:', error)
}
},
// 输入事件
onInput(e) {
this.setData({
keyword: e.detail.value
})
},
// 清除关键词
clearKeyword() {
this.setData({
keyword: '',
hasSearched: false,
worksheets: []
})
},
// 执行搜索
async doSearch() {
const keyword = this.data.keyword.trim()
if (!keyword) return
// 保存搜索历史
this.saveHistory(keyword)
this.setData({
page: 1,
hasMore: true,
worksheets: [],
hasSearched: true
})
await this.loadResults()
},
// 点击历史或热门关键词搜索
searchHistory(e) {
const keyword = e.currentTarget.dataset.keyword
this.setData({ keyword })
this.doSearch()
},
// 加载搜索结果
async loadResults() {
if (this.data.loading) return
try {
this.setData({ loading: true })
const res = await searchWorksheets({
keyword: this.data.keyword,
page: this.data.page,
pageSize: this.data.pageSize
})
if (res.success) {
const newWorksheets = res.data.list || []
this.setData({
worksheets: this.data.page === 1 ? newWorksheets : [...this.data.worksheets, ...newWorksheets],
total: res.data.pagination?.total || 0,
hasMore: newWorksheets.length >= this.data.pageSize,
loading: false
})
}
} catch (error) {
console.error('搜索失败:', error)
this.setData({ loading: false })
}
},
// 加载更多
async loadMore() {
if (this.data.loading || !this.data.hasMore) return
this.setData({
page: this.data.page + 1
})
await this.loadResults()
},
// 清除历史
clearHistory() {
wx.showModal({
title: '提示',
content: '确定清除搜索历史吗?',
success: (res) => {
if (res.confirm) {
wx.removeStorageSync('searchHistory')
this.setData({ history: [] })
}
}
})
},
// 返回
goBack() {
wx.navigateBack()
},
// 跳转详情
goDetail(e) {
const id = e.currentTarget.dataset.id
wx.navigateTo({
url: `/pages/detail/detail?id=${id}`
})
}
}))