返回

小程序历史搜索功能,让用户轻松找回记忆里的宝藏

前端

在小程序中运用 wx.setStorage 实现历史搜索功能

实现原理

小程序的历史搜索功能依赖于将用户的搜索记录存储在本地。当用户输入并确认搜索内容后,该内容会被存储起来。当用户再次使用该小程序时,即可从本地检索到历史搜索记录。

步骤分解

1. 前置准备

  • 搭建一个小程序项目
  • 创建一个用于用户输入搜索内容的文本框
  • 创建一个用于触发搜索的按钮
  • 创建一个列表用于展示搜索记录

2. 存储搜索记录

借助 wx.setStorage 方法,可将用户的搜索内容存储为本地数据。

wx.setStorage({
  key: 'searchHistory',
  data: searchContent
});

3. 获取搜索记录

使用 wx.getStorage 方法从本地检索搜索记录。

wx.getStorage({
  key: 'searchHistory',
  success: function (res) {
    var searchHistory = res.data;
  },
});

4. 展示搜索记录

利用 wx.setData 方法将获取到的搜索记录显示在列表中。

wx.setData({
  searchHistory: searchHistory,
});

5. 删除搜索记录

通过 wx.removeStorage 方法可以删除特定的搜索记录。

wx.removeStorage({
  key: 'searchHistory',
  success: function (res) {
    console.log('搜索记录已删除');
  },
});

完整代码示例

Page({
  data: {
    searchHistory: [],
  },
  onLoad: function () {
    this.getSearchHistory();
  },
  onSearch: function (e) {
    var searchContent = e.detail.value;
    this.setSearchHistory(searchContent);
    wx.navigateTo({
      url: 'result?searchContent=' + searchContent,
    });
  },
  setSearchHistory: function (searchContent) {
    wx.getStorage({
      key: 'searchHistory',
      success: function (res) {
        var searchHistory = res.data;
        searchHistory.unshift(searchContent);
        wx.setStorage({
          key: 'searchHistory',
          data: searchHistory,
        });
      },
      fail: function () {
        wx.setStorage({
          key: 'searchHistory',
          data: [searchContent],
        });
      },
    });
  },
  getSearchHistory: function () {
    wx.getStorage({
      key: 'searchHistory',
      success: function (res) {
        this.setData({
          searchHistory: res.data,
        });
      }.bind(this),
    });
  },
  onDeleteSearchHistory: function () {
    wx.removeStorage({
      key: 'searchHistory',
      success: function (res) {
        this.setData({
          searchHistory: [],
        });
      }.bind(this),
    });
  },
});

常见问题解答

1. 为什么我的搜索记录没有显示出来?

  • 检查 wx.setStoragewx.getStorage 方法是否正确使用。
  • 确保 key 值与存储和检索记录时使用的值相同。

2. 如何限制搜索记录的数量?

  • setSearchHistory 函数中,通过截取数组前几个元素来限制记录数量。

3. 用户可以编辑或删除搜索记录吗?

  • 可以通过自定义界面和事件处理程序来实现这些功能。

4. 搜索记录会在小程序卸载后保留吗?

  • 是的,搜索记录存储在本地,因此即使小程序卸载后也不会丢失。

5. 我可以用 wx.setStorageSync 代替 wx.setStorage 吗?

  • 不建议这样做,因为 wx.setStorageSync 是同步操作,可能会导致小程序卡顿。