微信小程序(三十四)搜索框-带历史记录

注释很详细,直接上代码

新增内容:
1.搜索框基本模板
2.历史记录基本模板
3.细节处理

源码:

index.wxml



 
<view class="history">
  <view class="search-bar">
    
    <input type="text"  model:value="{{keyword}}" />
    <text class="label" bind:tap="onSearch">搜索text>
  view>
  <view class="title" wx:if="{{keywords.length!==0}}"> 
    历史搜索 
    <text class="icon-delete" bind:tap="onClear">xtext>
  view>
  <view class="keywords">
    <navigator url="/pages/logs/logs" wx:for="{{keywords}}" wx:key="*this" >
        {{item}}
    navigator>
  view>
view>

index.wxss

input {
    padding: 14rpx 20rpx 10rpx;
    border: 2rpx solid #ddd;
    border-radius: 10rpx;
  }

  .history {
    margin-top: 20rpx;
    padding: 30rpx 20rpx;
    border-radius: 10rpx;
    background-color: #fff;
  }
  
  .history .search-bar {
    display: flex;
  }
  
  .history .search-bar .label {
    width: 90rpx;
    margin-right: 10rpx;
    text-align: right;
    line-height: 70rpx;
  }
  
  .history .search-bar input {
    flex: 1;
    padding-left: 40rpx;
    border-radius: 60rpx;
  }
  
  .history .title {
    display: flex;
    justify-content: space-between;
    margin-top: 30rpx;
    padding-left: 20rpx;
    font-size: 30rpx;
  }
  
  .history .title .icon-delete {
    width: 36rpx;
    height: 36rpx;
    text-align: center;
    line-height: 32rpx;
    border-radius: 50%;
    color: #fff;
    transform: scale(0.9);
    background-color: #ccc;
  }
  
  .history .keywords {
    display: flex;
    flex-wrap: wrap;
    margin-top: 10rpx;
    border-radius: 10rpx;
  }
  
  .history .keywords navigator {
    margin-right: 20rpx;
    margin-top: 20rpx;
    padding: 8rpx 28rpx;
    border-radius: 50rpx;
    background-color: #f7f6f7;
    font-size: 28rpx;
  }

index.js


Page({
    //数据
    data:{
        // 搜索框内容,使用的是简易的双向绑定
        //温习一下:第一层才能进行双向绑定
        keyword:'',

        //历史搜索的数组
        keywords:[]
    },
    //点击搜索按钮
    onSearch(){
        // this.data.keyword获取数据,
        //trim去除字符串前后多余空格
        const keyword=this.data.keyword.trim()
        //console.log(keyword)

        //非空判断
        if(keyword==='')
        {
            return wx.showToast({
              icon:'none',
              title: '请输入搜索内容',
            })
        }

       

        //在数组增加内容
        //push是增加在后面,unshift是在前面,历史记录当然是新的在前面
        //这个不会自动更新视图而微信小程序没用提供手动更新视图的api所以不用这个方法
        /* 
        this.data.keywords.unshift(keyword)
        */
       
       //增加数组长度的步骤也可以使用展开运算符
       const arr=[keyword,...this.data.keywords]

        this.setData({
            //先转化为set去重
            //然后重新转化为数组
            keywords:Array.from(new Set(arr)),

            //搜索完成清空搜索框
            keyword:''
        })

        console.log(this.data.keywords)
    },
    //清空历史记录
    onClear(){
        //清空历史记录数组
        this.setData({
            keywords:[]
        })
    }
})

效果演示:(历史记录第一个框也是有颜色的,可能是截图软件帧率 的问题)

微信小程序(三十四)搜索框-带历史记录_第1张图片

你可能感兴趣的:(微信小程序,微信小程序,小程序)