微信小程序搜索建议富文本的实现

289 阅读1分钟

微信小程序搜索建议富文本的实现

封装字符串转换的函数 stringToNodes

export default function stringToNodes(keyword, value) {
  const nodes = []
  if (keyword.toUpperCase().startsWith(value.toUpperCase())) {
    // 搜索建议与搜索框相同的字符
    const key1 = keyword.slice(0, value.length)
    const node1 = {
      name: 'span',
      attrs: { style: 'color: #26ce8a; font-size: 14px;' },
      children: [{ type: 'text', text: key1 }]
    }
    nodes.push(node1)

    // 后面的不同字符
    const key2 = keyword.slice(value.length)
    const node2 = {
      name: 'span',
      attrs: { style: 'color: #000000; font-size: 14px;' },
      children: [{ type: 'text', text: key2 }]
    }
    nodes.push(node2)
  } else {
    // 搜索内容与推荐没有相同的字符
    const node = {
      name: 'span',
      attrs: { style: 'color: #000000; font-size: 14px;' },
      children: [{ type: 'text', text: keyword }]
    }
    nodes.push(node)
  }
  return nodes
}

js中调用例子

 // 1.获取建议的关键词歌曲
 const suggestSongs = res.result.allMatch

 // 2.转成 nodes 节点
 const suggestKeywords = suggestSongs.map((item) => item.keyword)
 const suggestSongsNodes = []
 for (const keyword of suggestKeywords) {
   // 调用封装的 stringToNodes 函数对每一个搜索建议词进行处理
   const nodes = stringToNodes(keyword, searchValue)
   suggestSongsNodes.push(nodes)
 }
 // 3.保存处理好的数据
 this.setData({ suggestSongsNodes })

wxml中进行渲染

 <block wx:for="{{suggestSongs}}" wx:key="keyword">
     <view class="item">
       <!-- 利用遍历的 index 渲染生成后的数据 -->
       <rich-text nodes="{{suggestSongsNodes[index]}}"></rich-text>
     </view>
   </block>