微信小店联盟带货小程序

index.js 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. // pages/search/index.js
  2. Page({
  3. data: {
  4. keyword: '',
  5. searchHistory: [],
  6. hotSearches: [
  7. 'iPhone 14 Pro Max',
  8. '华为 Mate60 Pro',
  9. '小米14 Pro',
  10. 'MacBook Pro',
  11. 'iPad Pro',
  12. 'Apple Watch',
  13. 'AirPods Pro',
  14. 'Switch OLED'
  15. ],
  16. suggestions: []
  17. },
  18. onLoad() {
  19. // 获取搜索历史
  20. const history = wx.getStorageSync('searchHistory') || []
  21. this.setData({ searchHistory: history })
  22. },
  23. // 输入关键词
  24. onInput(e) {
  25. const keyword = e.detail.value.trim()
  26. this.setData({ keyword })
  27. if (keyword) {
  28. this.getSuggestions(keyword)
  29. } else {
  30. this.setData({ suggestions: [] })
  31. }
  32. },
  33. // 获取搜索建议
  34. getSuggestions(keyword) {
  35. // 模拟搜索建议
  36. const suggestions = this.data.hotSearches.filter(item =>
  37. item.toLowerCase().includes(keyword.toLowerCase())
  38. )
  39. this.setData({ suggestions })
  40. },
  41. // 执行搜索
  42. onSearch(e) {
  43. const keyword = (e.detail?.value || this.data.keyword).trim()
  44. if (!keyword) return
  45. this.saveSearchHistory(keyword)
  46. this.navigateToResult(keyword)
  47. },
  48. // 点击标签搜索
  49. onTagClick(e) {
  50. const { keyword } = e.currentTarget.dataset
  51. this.setData({ keyword })
  52. this.saveSearchHistory(keyword)
  53. this.navigateToResult(keyword)
  54. },
  55. // 保存搜索历史
  56. saveSearchHistory(keyword) {
  57. let history = this.data.searchHistory
  58. // 移除已存在的相同关键词
  59. history = history.filter(item => item !== keyword)
  60. // 将新关键词添加到开头
  61. history.unshift(keyword)
  62. // 只保留最近10条
  63. history = history.slice(0, 10)
  64. this.setData({ searchHistory: history })
  65. wx.setStorageSync('searchHistory', history)
  66. },
  67. // 清空搜索历史
  68. clearHistory() {
  69. wx.showModal({
  70. title: '提示',
  71. content: '确定要清空搜索历史吗?',
  72. success: (res) => {
  73. if (res.confirm) {
  74. this.setData({ searchHistory: [] })
  75. wx.removeStorageSync('searchHistory')
  76. }
  77. }
  78. })
  79. },
  80. // 清除关键词
  81. clearKeyword() {
  82. this.setData({
  83. keyword: '',
  84. suggestions: []
  85. })
  86. },
  87. // 取消搜索
  88. onCancel() {
  89. wx.navigateBack()
  90. },
  91. // 跳转到搜索结果页
  92. navigateToResult(keyword) {
  93. wx.navigateTo({
  94. url: `/pages/search/result?keyword=${encodeURIComponent(keyword)}`
  95. })
  96. }
  97. })