目录

uni-app搜索

uni-app:搜索

创建 search 分支

运行如下的命令,基于 master 分支在本地创建 search 子分支,用来开发搜索相关的功能:

git checkout -b search

https://i-blog.csdnimg.cn/blog_migrate/a9d46c340ffc6cd1287b2420885e255e.png

自定义搜索组件

自定义 my-search 组件

最新版本的没有components,自己需要右键组件创建

https://i-blog.csdnimg.cn/blog_migrate/217e33f7b72846aa4dca1ab65ea0ffe1.png

https://i-blog.csdnimg.cn/blog_migrate/4d088811e72143adf65aea51574a5451.png 在分类页面的 UI 结构中,直接以标签的形式使用 my-search 自定义组件:

https://i-blog.csdnimg.cn/blog_migrate/6c28dd65479f3ed8e8a63dcc175e761c.png

<!-- 使用自定义的搜索组件 -->
<my-search></my-search>

定义 my-search 组件的 UI 结构如下:

https://i-blog.csdnimg.cn/blog_migrate/363f0fd573aea0f6d1e38e75bbec0d60.png

uni-app给我们制定好了ui样式

<template>
  <view class="my-search-container">
    <!-- 使用 view 组件模拟 input 输入框的样式 -->
    <view class="my-search-box">
      <uni-icons type="search" size="17"></uni-icons>
      <text class="placeholder">搜索</text>
    </view>
  </view>
</template>

注意:在当前组件中,我们使用 view 组件模拟 input 输入框的效果;并不会在页面上渲染真正的 input 输入框

美化自定义 search 组件的样式:

.my-search-container {
  background-color: #c00000;
  height: 50px;
  padding: 0 10px;
  display: flex;
  align-items: center;
}

.my-search-box {
  height: 36px;
  background-color: #ffffff;
  border-radius: 15px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;

  .placeholder {
    font-size: 15px;
    margin-left: 5px;
  }
}

https://i-blog.csdnimg.cn/blog_migrate/ae88ee206cf710816518bf180ce330f5.png

https://i-blog.csdnimg.cn/blog_migrate/6aba9cbebd70bf031dd542e0c7e99d2f.png

由于自定义的 my-search 组件高度为 50px ,因此,需要重新计算分类页面窗口的可用高度:

https://i-blog.csdnimg.cn/blog_migrate/9f39cacff5c58d8734e21b362a0ac34a.png

有个bug,外面的原本是我们的可用高度,但是搜索又占了50高度,现在的可用高度应该是里面的线,因此我们要减去搜索框的高度

onLoad() {
  const sysInfo = uni.getSystemInfoSync()
  // 可用高度 = 屏幕高度 - navigationBar高度 - tabBar高度 - 自定义的search组件高度
  this.wh = sysInfo.windowHeight - 50
}

https://i-blog.csdnimg.cn/blog_migrate/cc480a2bb41648546bbdd883b4960559.png

通过自定义属性增强组件的通用性

为了增强组件的通用性,我们允许使用者自定义搜索组件的 背景颜色圆角尺寸

  1. 通过 props 定义 bgcolorradius 两个属性,并指定值类型和属性默认值:
props: {
  // 背景颜色
  bgcolor: {
    type: String,
    default: '#C00000'
  },
  // 圆角尺寸
  radius: {
    type: Number,
    // 单位是 px
    default: 18
  }
}

https://i-blog.csdnimg.cn/blog_migrate/31aa88df5f96600e26fec7e0390af5b6.png

通过属性绑定的形式,为 .my-search-container 盒子和 .my-search-box 盒子动态绑定 style 属性:

<view class="my-search-container" :style="{'background-color': bgcolor}">
  <view class="my-search-box" :style="{'border-radius': radius + 'px'}">
    <uni-icons type="search" size="17"></uni-icons>
    <text class="placeholder">搜索</text>
  </view>
</view>

https://i-blog.csdnimg.cn/blog_migrate/2f060d23121616acebf472100fcecb81.png 就是在props中自定义了属性 以后可以直接给组件传值更加方便

移除对应 scss 样式中的 背景颜色圆角尺寸

.my-search-container {
  // 移除背景颜色,改由 props 属性控制
  // background-color: #C00000;
  height: 50px;
  padding: 0 10px;
  display: flex;
  align-items: center;
}

.my-search-box {
  height: 36px;
  background-color: #ffffff;
  // 移除圆角尺寸,改由 props 属性控制
  // border-radius: 15px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;

  .placeholder {
    font-size: 15px;
    margin-left: 5px;
  }
}

为自定义组件封装 click 事件

https://i-blog.csdnimg.cn/blog_migrate/a4fbb76957452bf4576e18f7ef43a0f2.png

在组件里是不能直接使用vue封装好的方法,需要在组件内部先自定义好方法,然后通过this.@emit()方法把页面的事件传递到组件中执行

my-search 自定义组件内部,给类名为 .my-search-boxview 绑定 click 事件处理函数:

<view class="my-search-box" :style="{'border-radius': radius + 'px'}" @click="searchBoxHandler">
  <uni-icons type="search" size="17"></uni-icons>
  <text class="placeholder">搜索</text>
</view>

my-search 自定义组件的 methods 节点中,声明事件处理函数如下:

methods: {
  // 点击了模拟的 input 输入框
  searchBoxHandler() {
    // 触发外界通过 @click 绑定的 click 事件处理函数
    this.$emit('click')
  }
}

在分类页面中使用 my-search 自定义组件时,即可通过 @click 为其绑定点击事件处理函数:

<!-- 使用自定义的搜索组件 -->
<my-search @click="gotoSearch"></my-search>

同时在分类页面中,定义 gotoSearch 事件处理函数如下:

methods: {
   // 跳转到分包中的搜索页面
   gotoSearch() {
     uni.navigateTo({
       url: '/subpkg/search/search'
     })
   }
}

https://i-blog.csdnimg.cn/blog_migrate/ca55733e38cd919f411a608729cbbc80.png

实现首页搜索组件的吸顶效果

吸顶效果指的是随的滚动条变化,上面的搜索框不会消失

在 home 首页定义如下的 UI 结构:

<!-- 使用自定义的搜索组件 -->
<view class="search-box">
  <my-search @click="gotoSearch"></my-search>
</view>

在 home 首页定义如下的事件处理函数:

gotoSearch() {
  uni.navigateTo({
    url: '/subpkg/search/search'
  })
}

通过如下的样式实现吸顶的效果:

.search-box {
  // 设置定位效果为“吸顶”
  position: sticky;
  // 吸顶的“位置”
  top: 0;
  // 提高层级,防止被轮播图覆盖
  z-index: 999;
}

https://i-blog.csdnimg.cn/blog_migrate/243b824ddbd29cd190300de72f8e09d0.png

搜索建议

https://i-blog.csdnimg.cn/blog_migrate/0841d985d352afb90c5dfa59ad0fb427.png

渲染搜索页面的基本结构

定义如下的 UI 结构:

<view class="search-box">
  <!-- 使用 uni-ui 提供的搜索组件 -->
  <uni-search-bar @input="input" :radius="100" cancelButton="none"></uni-search-bar>
</view>

https://i-blog.csdnimg.cn/blog_migrate/1361c4e0eca1371c0a706bb1b0a93d61.png

修改 components -> uni-search-bar -> uni-search-bar.vue 组件,将默认的白色搜索背景改为 #C00000 的红色背景:

.uni-searchbar {
  /* #ifndef APP-NVUE */
  display: flex;
  /* #endif */
  flex-direction: row;
  position: relative;
  padding: 16rpx;
  /* 将默认的 #FFFFFF 改为 #C00000 */
  background-color: #c00000;
}

https://i-blog.csdnimg.cn/blog_migrate/2b06c95c216b813c418a7d754bc55331.png 实现搜索框的吸顶效果:

.search-box {
  position: sticky;
  top: 0;
  z-index: 999;
}

https://i-blog.csdnimg.cn/blog_migrate/8103e722f2ebf5015f6188e0122ecdb2.png

定义如下的 input 事件处理函数:

methods: {
      input(e) {
        // e.value 是最新的搜索内容
        console.log(e.valueOf())
      }
    }

现在要用e.valueOf()  注意O是大写

https://i-blog.csdnimg.cn/blog_migrate/e4eaaee90cc7d088ba93a478ec70caa5.png

实现搜索框自动获取焦点

修改 components -> uni-search-bar -> uni-search-bar.vue 组件,把 data 数据中的 showshowSync 的值,从默认的 false 改为 true 即可:

data() {
  return {
    show: true,
    showSync: true,
    searchVal: ""
  }
}

https://i-blog.csdnimg.cn/blog_migrate/42f921304565790f2f81f5f27da1133f.png

  1. 使用手机扫码预览,即可在真机上查看效果。

实现搜索框的防抖处理

在 data 中定义防抖的延时器 timerId 如下:

data() {
  return {
    // 延时器的 timerId
    timer: null,
    // 搜索关键词
    kw: ''
  }
}

修改 input 事件处理函数如下:

input(e) {
  // 清除 timer 对应的延时器
  clearTimeout(this.timer)
  // 重新启动一个延时器,并把 timerId 赋值给 this.timer
  this.timer = setTimeout(() => {
    // 如果 500 毫秒内,没有触发新的输入事件,则为搜索关键词赋值
    this.kw = e.value
    console.log(this.kw)
  }, 500)
}

根据关键词查询搜索建议列表

https://i-blog.csdnimg.cn/blog_migrate/6ec8c64201f2703f9f3e88bbb1203d66.png

在 data 中定义如下的数据节点,用来存放搜索建议的列表数据:

data() {
  return {
    // 搜索结果列表
    searchResults: []
  }
}

在防抖的 setTimeout 中,调用 getSearchList 方法获取搜索建议列表:

this.timer = setTimeout(() => {
  this.kw = e.value
  // 根据关键词,查询搜索建议列表
  this.getSearchList()
}, 500)

methods 中定义 getSearchList 方法如下:

// 根据搜索关键词,搜索商品建议列表
async getSearchList() {
  // 判断关键词是否为空
  if (this.kw === '') {
    this.searchResults = []
    return
  }
  // 发起请求,获取搜索建议列表
  const { data: res } = await uni.$http.get('/api/public/v1/goods/qsearch', { query: this.kw })
  if (res.meta.status !== 200) return uni.$showMsg()
  this.searchResults = res.message
}

https://i-blog.csdnimg.cn/blog_migrate/2c7d6314d3308dd3f4950f1faceaeb6b.png

渲染搜索建议列表

定义如下的 UI 结构:

<!-- 搜索建议列表 -->
<view class="sugg-list">
  <view class="sugg-item" v-for="(item, i) in searchResults" :key="i" @click="gotoDetail(item.goods_id)">
    <view class="goods-name">{{item.goods_name}}</view>
    <uni-icons type="arrowright" size="16"></uni-icons>
  </view>
</view>

美化搜索建议列表:

.sugg-list {
  padding: 0 5px;

  .sugg-item {
    font-size: 12px;
    padding: 13px 0;
    border-bottom: 1px solid #efefef;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .goods-name {
      // 文字不允许换行(单行文本)
      white-space: nowrap;
      // 溢出部分隐藏
      overflow: hidden;
      // 文本溢出后,使用 ... 代替
      text-overflow: ellipsis;
      margin-right: 3px;
    }
  }
}

https://i-blog.csdnimg.cn/blog_migrate/76b251043fb39f7b7194de8769a55030.png

点击搜索建议的 Item 项,跳转到商品详情页面:

gotoDetail(goods_id) {
  uni.navigateTo({
    // 指定详情页面的 URL 地址,并传递 goods_id 参数
    url: '/subpkg/goods_detail/goods_detail?goods_id=' + goods_id
  })
}

https://i-blog.csdnimg.cn/blog_migrate/0b54be4f143cdb0284f8a79c170f3925.png

https://i-blog.csdnimg.cn/blog_migrate/70808fa172f3959f88546713019cd3ca.png

搜索历史

渲染搜索历史记录的基本结构

在 data 中定义搜索历史的 假数据

data() {
  return {
    // 搜索关键词的历史记录
    historyList: ['a', 'app', 'apple']
  }
}

渲染搜索历史区域的 UI 结构:

<!-- 搜索历史 -->
<view class="history-box">
  <!-- 标题区域 -->
  <view class="history-title">
    <text>搜索历史</text>
    <uni-icons type="trash" size="17"></uni-icons>
  </view>
  <!-- 列表区域 -->
  <view class="history-list">
    <uni-tag :text="item" v-for="(item, i) in historyList" :key="i"></uni-tag>
  </view>
</view>

美化搜索历史区域的样式:

.history-box {
  padding: 0 5px;

  .history-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 40px;
    font-size: 13px;
    border-bottom: 1px solid #efefef;
  }

  .history-list {
    display: flex;
    flex-wrap: wrap;

    .uni-tag {
      margin-top: 5px;
      margin-right: 5px;
    }
  }
}

https://i-blog.csdnimg.cn/blog_migrate/010c0318967847b3ba10eed0960c0523.png

实现搜索建议和搜索历史的按需展示

  1. 当搜索结果列表的长度 不为 0 的时候( searchResults.length !== 0 ),需要展示搜索建议区域,隐藏搜索历史区域
  2. 当搜索结果列表的长度 等于 0 的时候( searchResults.length === 0 ),需要隐藏搜索建议区域,展示搜索历史区域

使用 v-ifv-else 控制这两个区域的显示和隐藏,示例代码如下:

<!-- 搜索建议列表 -->
<view class="sugg-list" v-if="searchResults.length !== 0">
  <!-- 省略其它代码... -->
</view>

<!-- 搜索历史 -->
<view class="history-box" v-else>
  <!-- 省略其它代码... -->
</view>

https://i-blog.csdnimg.cn/blog_migrate/95b98232190eed08806932be68527be0.gif

将搜索关键词存入 historyList

直接将搜索关键词 pushhistoryList 数组中即可

methods: {
  // 根据搜索关键词,搜索商品建议列表
  async getSearchList() {
    // 省略其它不必要的代码...

    // 1. 查询到搜索建议之后,调用 saveSearchHistory() 方法保存搜索关键词
    this.saveSearchHistory()
  },
  // 2. 保存搜索关键词的方法
  saveSearchHistory() {
    // 2.1 直接把搜索关键词 push 到 historyList 数组中
    this.historyList.push(this.kw)
  }
}
  1. 上述实现思路存在的问题:

    • 关键词 前后顺序 的问题(可以调用数组的 reverse() 方法 对数组进行反转)
    • 关键词 重复 的问题(可以使用 进行 去重操作
    • https://i-blog.csdnimg.cn/blog_migrate/ea4635d4ec5558a3503f214e5dd41228.png

解决关键字前后顺序的问题

data 中的 historyList 不做任何修改,依然使用 push 进行 末尾追加

定义一个计算属性 historys ,将 historyList 数组 reverse 反转之后,就是此计算属性的值:

computed: {
  historys() {
    // 注意:由于数组是引用类型,所以不要直接基于原数组调用 reverse 方法,以免修改原数组中元素的顺序
    // 而是应该新建一个内存无关的数组,再进行 reverse 反转
    return [...this.historyList].reverse()
  }
}

页面中渲染搜索关键词的时候,不再使用 data 中的 historyList ,而是使用计算属性 historys

<view class="history-list">
  <uni-tag :text="item" v-for="(item, i) in historys" :key="i"></uni-tag>
</view>

https://i-blog.csdnimg.cn/blog_migrate/ec30295c19826e110696e6370c32b04c.png

解决关键词重复的问题

修改 saveSearchHistory 方法如下:

// 保存搜索关键词为历史记录
saveSearchHistory() {
  // this.historyList.push(this.kw)

  // 1. 将 Array 数组转化为 Set 对象
  const set = new Set(this.historyList)
  // 2. 调用 Set 对象的 delete 方法,移除对应的元素
  set.delete(this.kw)
  // 3. 调用 Set 对象的 add 方法,向 Set 中添加元素
  set.add(this.kw)
  // 4. 将 Set 对象转化为 Array 数组
  this.historyList = Array.from(set)
}

https://i-blog.csdnimg.cn/blog_migrate/493f2319755e88a44167b777b2a897d0.png

将搜索历史记录持久化存储到本地

修改 saveSearchHistory 方法如下:

// 保存搜索关键词为历史记录
saveSearchHistory() {
  const set = new Set(this.historyList)
  set.delete(this.kw)
  set.add(this.kw)
  this.historyList = Array.from(set)
  // 调用 uni.setStorageSync(key, value) 将搜索历史记录持久化存储到本地
  uni.setStorageSync('kw', JSON.stringify(this.historyList))
}

onLoad 生命周期函数中,加载本地存储的搜索历史记录:

onLoad() {
  this.historyList = JSON.parse(uni.getStorageSync('kw') || '[]')
}

https://i-blog.csdnimg.cn/blog_migrate/b86bb0329a5578c9b52e24a7b4f9a9f2.png

清空搜索历史记录

为清空的图标按钮绑定 click 事件:

<uni-icons type="trash" size="17" @click="cleanHistory"></uni-icons>

methods 中定义 cleanHistory 处理函数:

// 清空搜索历史记录
cleanHistory() {
  // 清空 data 中保存的搜索历史
  this.historyList = []
  // 清空本地存储中记录的搜索历史
  uni.setStorageSync('kw', '[]')
}

https://i-blog.csdnimg.cn/blog_migrate/e9bd33668abc1987829410d4e628f14c.png

这里应该用uni.removeStorageSync(‘kw’)

点击搜索历史跳转到商品列表页面

为搜索历史的 Item 项绑定 click 事件处理函数:

<uni-tag :text="item" v-for="(item, i) in historys" :key="i" @click="gotoGoodsList(item)"></uni-tag>

methods 中定义 gotoGoodsList 处理函数:

// 点击跳转到商品列表页面
gotoGoodsList(kw) {
  uni.navigateTo({
    url: '/subpkg/goods_list/goods_list?query=' + kw
  })
}

https://i-blog.csdnimg.cn/blog_migrate/074fceb6665d1ebee70dd48f73106fbf.png

分支的合并与提交

search 分支进行本地提交:

git add .
git commit -m "完成了搜索功能的开发"

将本地的 search 分支推送到码云:

git push -u origin search

将本地 search 分支中的代码合并到 master 分支:

git checkout master
git merge search
git push

删除本地的 search 分支:

git branch -d search

https://i-blog.csdnimg.cn/blog_migrate/78b0b4ba5660598973634af03ce52b90.png