微信小程序 搜索框 保留历史搜索记录

334 阅读1分钟

image.png

<template>
  <view>
    <view class="p-10 bg-white">
      <u-search v-model="keyword" @custom="search" :show-action="true" @search="search" action-text="搜索"></u-search>
      <view class="mt-20">
        <view class="flex justify-center justify-between">
          <view class="text-blod-500 text-16">
            搜索历史
          </view>
          <view v-if="lists.length" @click="clearLists">清空搜索记录</view>
        </view>
        <view class="flex flex-wrap">
          <view :key="index" class="mr-5 mt-10" v-for="(item,index) in lists">
            <u-tag @click="toLists(item)" :border-color="$m.color('grey')" :color="$m.color('grey')" :bg-color="$m.color('white')" :text="item" type="info" shape="circle" />
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data(){
    return {
      lists:[],
      keyword:'',
    }
  },
  onShow(){
   this.lists = uni.getStorageSync('searchHistory') || []
  },
  methods:{
    toLists(keyword){
      this.keyword = keyword;
      this.$m.jumpPage('/pages/goods/lists',{keyword,isFilter:true})
    },
    clearLists(){
      const that = this;
      uni.showModal({
        title:'温馨提示',
        content:'确认清空搜索记录?',
        success(res){
          if(res.confirm){
            that.lists = [];
            uni.removeStorageSync('searchHistory');
          }
        }
      })
    },
    search(){
			console.log('search')
      if(!this.keyword.trim()){
        this.$m.toast('请输入关键字搜索');
        this.keyword = '';
        return
      }
      if(this.lists.indexOf(this.keyword)!==-1){
        this.lists.splice(this.lists.indexOf(this.keyword),1)
      }else if(this.lists.length===10){
        this.lists.splice(this.lists.length-1,1)
      }
      this.lists.unshift(this.keyword);
      uni.setStorageSync('searchHistory',this.lists);
      this.$m.jumpPage('/pages/goods/lists',{keyword:this.keyword,isFilter:true})
    },
  },
};
</script>

<style scoped>

</style>