【微信小程序】4plus|搜索框-历史搜索 | 我的咖啡店-综合实训

发布于:2025-02-11 ⋅ 阅读:(159) ⋅ 点赞:(0)

升级版1-清空全部的再次确认

实现功能:

  1. 历史搜索记录
  2. 展示-历史搜索记录展示10条
  3. 点击跳转-点击历史搜索记录可同步到搜索框并自动搜索
  4. 全部删除-可一次性全部删除历史搜索记录
  5. 全部删除-有再次确认操作

展示

进行搜索后留下搜索记录

点击垃圾桶图标,显示【清空全部】

点击【清空全部】后,历史记录被清空

1. 页面初始数据设置

search.js 中,我们定义了页面的初始数据,包括搜索历史列表 historyList、搜索关键词 keyword 以及控制清空按钮显示的 showClearAllButton

// pages/search/search.js
Page({
  data: {
    historyList: [],
    keyword: "",
    showClearAllButton: false
  },
  // ...其他函数...
});

2. 显示清空全部按钮

个函数通过修改 showClearAllButton 的值来控制“清空全部”按钮的显示和隐藏。

  // 显示清空全部按钮
  showClearAll() {
    this.setData({
      showClearAllButton: true
    });
  },
  • this.setData 是微信小程序中用于更新页面数据的方法。当 setData 被调用时,它不仅会更新页面的数据,还会触发页面的重新渲染,以反映新的数据状态。
  • showClearAllButton 是页面数据(data)中的一个属性,用于控制“清空全部”按钮的显示。当其值为 true 时,按钮显示;为 false 时,按钮隐藏。

3. 清空搜索历史

clearAllHistory 函数中,我们使用 wx.showModal 来显示一个确认对话框,确保用户真的想要清空搜索历史。

// pages/search/search.js
clearAllHistory() {
  wx.showModal({
    title: '清空历史',
    content: '确定要清空所有搜索历史吗?',
    success: (res) => {
      if (res.confirm) {
        this.setData({
          historyList: [],
          showClearAllButton: false
        });
        wx.removeStorageSync('searchKeyArr');
      }
    }
  });
},

4. WXML 结构

search.wxml 中,我们使用条件渲染来控制清空按钮的显示和隐藏。

<!--pages/search/search.wxml-->
<view class="search">
  <!-- 搜索框开始 -->
  <van-search ...>
    <view slot="action" bind:tap="onSearch" style="padding:0 30rpx">搜索</view>
  </van-search>
  <!-- 搜索框结束 -->
  <!-- 搜索历史视图开始 -->
  <view class="history" wx:if="{
  {historyList.length}}">
    <!-- 标题 -->
    <view class="title">
      <view class="text">搜索历史</view>
      <view class="remove" wx:if="{
  {!showClearAllButton}}" bindtap="showClearAll">
        <van-icon name="delete-o" size="21" />
      </view>
      <view class="clear-all" wx:if="{
  {showClearAllButton}}" bindtap="clearAllHistory">
        清空全部
      </view>
    </view>
    <!-- 内容区域 -->
    <view class="content">
      <!-- 循环显示搜索历

网站公告

今日签到

点亮在社区的每一天
去签到