小程序中实现本地搜索中将含有搜索关键字标红(用的uniApp)

WXML:

<view class="header">
  <input
    class="input"
    placeholder-class="uni-input-placeholder"
    placeholder="请输入搜索内容"
    v-model.trim="qString"
    @confirm="handleSearch"
    @input="handleValue"
  />
  <uni-icons class="icon" type="search" color="#B5B5B5" size="23" />
</view>
// 显示红色字体的标题
<rich-text :nodes="item.storeName | filterTitle(qString)" v-if="showRedText">
</rich-text>
<rich-text :nodes="item.storeName" v-else>
</rich-text>

 

JS:

数据:

 const storeList = [
  {
    id: 1,
    title: '咖啡哈哈哈哈嘿嘿嘿和嘿嘿',
    address: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
  },
  {
    id: 2,
    title: '上海的某某某咖啡哈哈哈',
    address: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
  }
 ]

data () {
  return {
    storeList, // 数据列表
    qString: '', // 搜索框的内容
    searchList: [], // 搜索出来的结果
    showRedText: false // 是否显示红色字体的标题
  }
},
created () {
  // 进页面的时候把数据赋值,用searchList来渲染
  this.searchList = this.storeList
},
filters: {
  // 标题的某些被搜索到的文字显示红色的过滤器
  filterTitle(val, key) {
    return key ? '<div class="uni-ellipsis uni-title">' + val.replace(key, '<span style="color:red;">' + key + '</span>') + '</div>' : '<div class="uni-ellipsis uni-title">' + val + '</div>'
  }
},
methods: {
  handleSearch () {
    let { storeList, qString } = this
    this.showRedText = true // 当点击搜索的时候再让字体变红
    // 搜索的时候当含有搜索的值的数据进行过滤---拿到新的数据
    this.searchList = storeList.filter(arg => arg.title.includes(qString))
  },
  handleValue (e) {
  // 当清空的时候恢复原来的数据
    if (!e.target.value) {
      this.searchList = this.storeList
    }
  }
}

posted @ 2021-03-02 17:40  搬砖的苦行僧  阅读(223)  评论(0编辑  收藏  举报