PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

深入讲解小程序中实现搜索功能的方法

青灯夜游
青灯夜游 转载
2021-09-06 19:25:39 9081浏览

小程序常见的搜索功能如何实现呢?下面本篇文章就来一步步带大家了解一下小程序中实现搜索功能的方法,希望对大家有所帮助!

在每个小程序开发的过程中,基本上都会配备有搜索功能,那么相对智能化的搜索功能是如何实现的呢,通过一段时间的学习,我已经学会比较全面的搜索框功能,来一起看看吧!

1.png

开发准备

效果展示

先来看看效果

2.gif

前期准备

云数据库导入一些数据用来测试搜索框功能

3.png

实现

在目录下面新建三个pages

index用来作为搜索框的第一个页面

search用来做具体搜索的页面

hotsearch是搜索内容的详情页面

首先我们先来看看搜索框第一个页面index的布局,这里主要介绍搜索框的内容,下面的其他内容就不在这儿赘述了

4.png

这是index.wxml代码

      <view class="search_1" bindtap="gotoSearch">
          <van-search 
          placeholder="搜索单品" disabled
          />
        </view>
      <view class="search_2">
        <view class="pic" bindtap="list" >
          <image src=""></image>
        </view>
      </view>
    </view>

5.png

这是搜索框的search.wxml代码

  <view class="dewu-search">
    <view class="return" >
      <view class="return_pic" bindtap="gotoindex">
        <image src=""></image>
      </view>
      <view class="txt">搜索</view>
    </view>
  </view>
  <van-search 
      value="{{value}}" 
      show-action 
      placeholder="输入商品名称、货号"
      bind:clear="onClear" 
      bind:search="onSearch"   
      bind:cancel="oncancel" 
      bind:change="onchange"
      bindtap="input"
      value="{{value}}"
    />
    <block wx:if="results.length > 0">
      <van-cell wx:for="{{results}}" wx:key="_id" title="{{item.title}}"  size="large"  />
    </block>
    <view class="page1" hidden="{{issuggest==true?&#39;hidden&#39;:&#39;&#39;}}" >
        <view class="bd">
          <view class="content">热门搜索</view>
          <view class="box">
            <view class="items">
              <view class="item" wx:for="{{goods}}"
              wx:key="index"  bindtap="hotsearch" data-id="{{item.id}}"
              >
              {{item.hot}}
              </view>
            </view>
          </view>
        </view>
        <view class="last">
          <view class="content">搜索历史</view>
          <view class="box">
            <view class="items">
              <view class="item" wx:for="{{historyList}}" wx:key="index" data-id="{{item.id}}" bindtap="gotohistoryList"
              wx:key="index">
                {{item.hot}}
              </view>
            </view>
          </view>
        </view>
    </view>
    <view class="page2"   hidden="{{issuggest==false?&#39;hidden&#39;:&#39;&#39;}}">
      <view class="content1">
        <view class="title" wx:for="{{goods1}}" data-id="{{item.id}}"
              wx:key="index"  bindtap="hotsearch" >
              {{item.hot}}
        </view>
      </view>
    </view>
</view>

js里面首先要引入云数据库里的数据

    const db = wx.cloud.database();
    const dewuCollection = db.collection(&#39;dewu&#39;);

要做到输入框发生改变时,弹出相关的内容,则需要两个page,当输入框有内容输入时,把隐藏的页面显示出来hidden="{{issuggest==false?'hidden':''}}"来判断是否要出现相关内容页面, 用indexOf判断e.detail(输入框内容)是否是在云数据库里存在的,如果是存在的,那么将这条数据存入一个数组里面,并且连接之前搜索后的数组,再使用 wx.setStorageSync();将输入框的数据存入到storage里面,然后再wx.getStorageSync()提取数据。

这是当输入框有数据的时候就会弹出详情页面,点击可以跳转到商品的详情页

6.png

这是搜索框的逻辑

    if(e.detail.length!=0){
        this.setData({
          issuggest:true,
        })
        var arr = [];
        console.log(this.data.goods.length);
            for (var i = 0; i < this.data.goods.length; i++) {
              if (this.data.goods[i].hot.indexOf(e.detail)>=0) {
                arr.push(this.data.goods[i]);
              }
              this.setData({
              goods1:arr,
           })
          }
    }
    else {
      console.log(&#39;succes&#39;);
      this.setData({
         issuggest:false
      })
    }
  },
    async onSearch(e){
    var arr1=new Array();
    var historyList=new Array();
    var storage=new Array();
    for (let i = 0; i < this.data.goods.length; i++){
      if(e.detail==this.data.goods[i].hot){
        arr1.push(this.data.goods[i]);
        console.log(arr1);
        break
      }
      else{
              arr1.push(e.detail);
              console.log(arr1);
        }
    }
    if(arr1.length>1){
      this.setData({
        storage:arr1.slice(arr1.length-1,arr1.length)
      })
    }
    else{
      console.log(arr1,&#39;要存进去的数据&#39;);
      this.setData({
        storage:arr1
      })
    }
    if(this.data.historyList !=[]){
      this.data.historyList = this.data.historyList.concat(this.data.storage);//连接
    }
    else{
      this.data.historyList=this.data.storage
    }
   wx.setStorageSync(&#39;historyList&#39;, this.data.historyList);
   this.setData({
    historyList:this.data.historyList
  })
  },

7.png

wx.navigateTo可以用来跳转到详细的页面,加上字符串模板,判断id的值,用数据来驱动页面,跳转到相同的页面不同的数据。

wx.navigateTo({
      url: `../hotsearch/hotsearch?id=`+id
    })

最后还要更新数据

     wx.showLoading({
       title: &#39;数据加载中...&#39;,
     })   
     setTimeout(()=>{
      wx.hideLoading()
       this.setData({
          goodsNav: nav,
          goodsList:List,
          recommend:List,
          goods2:this.data.historyList
       })
      },1000)
// console.log(goodsList,&#39;===========&#39;);
   },

注意不要忘记要在全局json或者局部页面json里引入需要使用的组件的地址

    "usingComponents": {
        "van-search":"./miniprogram_npm/@vant/weapp/search/index"
  },

扩展

这个自动跳转到导航栏中间的功能也是挺常用的

8.gif

这是wxml代码 最主要的是 scroll-x="true" 让导航栏在水平方向可以滑动scroll-with-animation="true"是让滑动产生动画,scroll-into-view="{{scrollTop}}"

      <scroll-view  scroll-x="true"
                 scroll-with-animation="true"
                 style="width:100%;" class="scroll-view_H " 
                 scroll-into-view="{{scrollTop}}">
        <view 
        wx:for="{{goodsNav}}"
        wx:key="index"
        id="{{item.id}}"
        data-index="{{index}}"
        data-type="{{item.type}}"
        bindtap="changegoods"
        class="scroll-view-item_H {{activeNavIndex == index?&#39;active&#39;: &#39;&#39;}}  "
        >
          <text>{{item.text}}</text>
        </view>
      </scroll-view>
    </view>

这是绑定在导航栏上面的事件 let {index, type} = e.currentTarget.dataset;提取到 index 和 type ,然后设置一个count作为前几个不动,然后拼接给id,把id的值传给scrollTop,让导航栏跳到scrollTop这个值,这个值就是在中间

     console.log(e);
    let {index, type} = e.currentTarget.dataset;
    console.log("index=" +index, "type="+type);
    this.setData({
      activeNavIndex:index
    })
    if (type == &#39;recommend&#39;) {
      this.setData({
        goodsList: this.data.recommend
      })
    } 
    else {
        let goods = this.data.recommend.filter((good) => good.camptype == type )
        this.setData({
          goodsList: goods
        })
        //console.log(this.data.goods)
      }
    
      var index1 = e.currentTarget.dataset.index;
      var count = 2;
      var id = "item"+(index1-count);//拼接id
      if(count == 2 && index1 < 3 || count == 3 && index1 < 2 || count == 4 && index1 < 3){
        id = "item0";
      }
      console.log("下标",index1,"---分类id名称",id)
      this.setData({
        scrollTop: id
      })
    },

这样再加上wxss后就可以达到效果了 不过这样的写有一个问题,就是当显示的内容为偶数时,如6,则不能正确的跳到正中间,会跳到3的位置,那样就有一点儿偏差,这个问题我暂时还没有解决,不知道有没有大佬知道这个怎么解决呢?

源码

这里有项目完整的源码,上面给出的是部分代码,如果有感兴趣的可以去看看完整源码

https://gitee.com/xinccc/fullstack_huoshan/tree/master/wxapp/dewu

总结

这是我第一次写一次稍微完整的项目,这里主要介绍了我在开发过程中遇到的主要困难,虽然总体来说没有什么难点,但是对我来说还是意义挺大的,有了一次这样的经历,让我发现了我还有很多内容需要学习,也感谢在我有困难时帮我指点迷津的老师和同学,如果你感觉这篇文章有get到你的地方,不妨给我点个赞,这将为我莫大的鼓励,各位大佬如果有什么指点的话,希望可以在评论区一起探讨学习。

更多编程相关知识,请访问:编程入门!!

声明:本文转载于:掘金社区,如有侵犯,请联系admin@php.cn删除