全栈项目|小书架|微信小程序-实现搜索功能

效果图

在这里插入图片描述

上图是小程序端实现的搜索功能效果图。 从图中能够看出点击首页搜索按钮便可进入搜索页面。css

布局样式是:搜索框 + 热搜内容 + 搜索列表。html

  • 搜索框使用 lin-ui 中的 Searchbar组件
  • 热搜内容的单个按钮使用 lin-ui 中的 Tag组件,而实现云标签样式的布局是用css样式控制。
  • 搜索列表使用 lin-ui 中的 WaterFlow布局组件

搜索框实现

在这里插入图片描述

搜索框就是照着 Searchbar组件 文档实现,所以wxml布局以下:小程序

<l-search-bar placeholder="搜索" bg-color="#F6F6F6" shape="circle" show-cancel="{{false}}" bind:linconfirm="bindSearch" />

有了搜索布局以后,就须要获取用户输入的内容,而后调用接口去搜索相关数据了。布局

bindSearch: function(e) {
    let that = this
    // 获取输入的信息
    let q = e.detail.value
    // 调用搜索书籍的接口
    bookModel.getSearchBooks(q, 0, 20)
      .then(res => {
        let data = res;
        if (data.length > 0) {
          that.setData({
            bookList: data
          });
          // 参数2 true表示清除原有数据
          wx.lin.renderWaterFlow(data, true, () => {
            console.log('渲染成功')
          })
        } else {
          that.setData({
            bookList: []
          });
        }
      })
  },

热搜实现

在这里插入图片描述

热搜布局主要使用 card组件 + Tag组件 渲染。ui

Card组件主要是提供左上角的提示文本以及背景圆角,而Tag组件主要显示热搜的结果。 wxml布局以下:this

<l-card type="primary" title="热门搜索" plaintext="{{true}}" full="{{true}}">
    <!-- 热搜 -->
    <view class="content">
      <block wx:for="{{hotBooks}}" wx:key="index">
        <view class="hot-search-item">
          <l-tag shape="circle" bind:lintap="toBookDetail" data-id="{{item.id}}">{{item.name}}</l-tag>
        </view>
      </block>
    </view>
  </l-card>

从布局中能够看出咱们须要传递hotBooks集合给页面,所以在js文件中须要请求热搜接口,获取到热搜数据而后赋值给hotBooks集合,伪代码以下:spa

bookModel.getHotSearchBooks()
      .then(res => {
        if (res.length > 0) {
          that.setData({
            hotBooks: res
          });
        } else {
          that.setData({
            hotBooks: []
          });
        }
      })

网格列表实现

在这里插入图片描述

网格布局是采用 WaterFlow布局组件 实现的。官方文档写的很好,看一遍基本就能当即使用了。3d

这里作了空视图的处理,也就是若是没搜索到数据会显示空视图,若是有数据才会显示网格布局。因此wxml的代码以下:code

<view class="book-container" wx:else>
  <!-- 搜索列表 -->
  <block wx:if="{{bookList.length > 0}}">
     <l-water-flow generic:l-water-flow-item="book-item" column-gap="20rpx" />
  </block>

  <block wx:else>
    <view class="empty-container">
      <image class="userinfo-avatar" src="../../images/sad.png" background-size="cover"></image>
      <view class="donut-container">空空如也</view>
    </view>
  </block>
</view>

上面的网格布局中的l-water-flow-item="book-item",指的是一个组件。 该组件就是网格中的每一本图书布局。实现起来都比较容易这里就很少介绍了。 可参考 WaterFlow布局组件 以及 小程序自定义组件component

以上就是本次的介绍。


扫码关注公众号,轻撩便可。

在这里插入图片描述

原文出处:https://www.cnblogs.com/gdragon/p/12014028.html

相关文章
相关标签/搜索