小程序:用Storage存儲用戶搜索歷史

今天在寫商品搜索時,要記錄用戶的搜索歷史。用setStorage建立一個數組,每次進入商品搜索頁面,加載。
代碼如下:
一:一進去先讀取history表

onLoad:function(){
    const that=this;
        wx.getStorage({
      key: 'history',
      success: function(res) {
        that.setData({
         recent_key:res.data
        });
      }
     });
  }

二:用戶輸入完畢,點擊搜索時觸發這個事件getGoodsList

<view class="search-input">
			<icon class="search-icon" type="search" size="16"></icon>
			<input type="text" placeholder="搜索商品名稱" confirm-type='search' value="{{inputValue}}"  bindconfirm="getGoodsList" />
		</view>

三:在這個事件裏存儲用戶輸入的商品名,其實還有發起搜索請求的作用,這裏不放了

 get_history:function(){
    const that=this;
   wx.getStorage({
      key: 'history',
      success: function(res) {
        that.setData({
         recent_key:res.data
        });
      }
     });

  },
 getGoodsList:function(e){
    //建立歷史記錄表
    this.setData({
      inputValue:e.detail.value
     })

     const inputValue=this.data.inputValue;
         let history=this.data.recent_key;
         history.push(inputValue)
       
       wx.setStorage({
        key:'history',
        data:history
       })

        this.get_history();//把storage的數據存到data裏
     }

四,刪除history表

<image src="/images/icon/icon-delete.png" bindtap="delete_recent"></image>
  delete_recent:function(){
    const that=this;
  wx.removeStorage({
  key: 'history',
  success (res) {
    that.setData({
      recent_key:[]
    })
  }
})
  },
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章