search.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. let timeId = null;
  2. Page({
  3. data: {
  4. history: [],
  5. hot: ['新鲜芹菜', '大红枣', '滋补桂圆干'],
  6. result: [
  7. {
  8. id: 1,
  9. url: '../details/details',
  10. thumb: '/image/s4.png',
  11. title: '瓜子 100g',
  12. price: 0.01
  13. },
  14. {
  15. id: 2,
  16. url: '../details/details',
  17. thumb: '/image/s5.png',
  18. title: '新鲜芹菜 500g',
  19. price: 0.02
  20. }
  21. ],
  22. showKeywords: false,
  23. keywords: ['山东肚脐橙', '湖南冰糖橙', '麻涌香蕉', '冰糖心苹果'],
  24. value: '',
  25. showResult: false,
  26. },
  27. cancelSearch() {
  28. this.setData({
  29. showResult: false,
  30. showKeywords: false,
  31. value: ''
  32. })
  33. },
  34. searchInput(e) {
  35. if(!e.detail.value){
  36. this.setData({
  37. showKeywords: false
  38. })
  39. }else{
  40. if(!this.data.showKeywords){
  41. timeId && clearTimeout(timeId);
  42. timeId = setTimeout(() => {
  43. this.setData({
  44. showKeywords: true
  45. })
  46. }, 1000)
  47. }
  48. }
  49. },
  50. keywordHandle(e) {
  51. const text = e.target.dataset.text;
  52. this.setData({
  53. value: text,
  54. showKeywords: false,
  55. showResult: true
  56. })
  57. this.historyHandle(text);
  58. },
  59. historyHandle(value) {
  60. let history = this.data.history;
  61. const idx = history.indexOf(value);
  62. if (idx === -1) {
  63. // 搜索记录只保留8个
  64. if (history.length > 7) {
  65. history.pop();
  66. }
  67. } else {
  68. history.splice(idx, 1);
  69. }
  70. history.unshift(value);
  71. wx.setStorageSync('history', JSON.stringify(history));
  72. this.setData({
  73. history
  74. });
  75. },
  76. onLoad() {
  77. const history = wx.getStorageSync('history');
  78. if (history) {
  79. this.setData({
  80. history: JSON.parse(history)
  81. })
  82. console.log(this.data.history);
  83. }
  84. }
  85. })