vue实现搜索关键字高亮

Recently i got a development assignment,it is interesting,below is a effect picture

在这里插入图片描述

wxml

<view class="resultBox" wx:if='{{keyword}}'>
      <view wx:for='{{searchList}}' wx:for-item='item' wx:key="{{index}}" class="resultItem">
        <text wx:for='{{item.title}}' wx:for-item='itm'  class="{{itm==keyword?'matchedText':''}}">{{itm}}</text>
      </view>
</view>

js

  data: {
    inputFocus: false,
    keyword: '',
    searchList: [{
      title: "入门指南入门的入门"
    }, {
      title: "高手的入门精髓"
    }, {
      title: "看看大佬入门网购经验"
    }]
  }

  keywordChange(e) {
    var that=this
    setTimeout(function(){
      that.showResult(e,that)
    },500)
  },
  showResult(e,that){
    var inputVal = e.detail.value
    that.setData({
      keyword: inputVal
    })
    var searchArray = that.data.searchList
    searchArray.forEach((item, index) => {
      item.title = item.title.split(inputVal).join('*' + inputVal + '*').split("*");
      console.log(item.title);
    })
    that.setData({
      searchList: searchArray
    })
  },
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现Vue 中的搜索框中输入关键字后,将匹配到的内容高亮显示,可以遵循以下步骤: 1. 在 data 中定义一个变量来保存搜索关键字。 2. 在模板中使用 input 元素来渲染搜索框,并为其绑定一个 input 事件来监听输入内容变化。 3. 在模板中渲染需要搜索的内容,并使用 v-html 指令将内容渲染为 HTML。 4. 使用 computed 属性来实现关键字高亮的逻辑。在 computed 中定义一个方法,接收需要搜索的内容和搜索关键字,并使用正则表达式将匹配到的内容用 <span> 标签包裹,从而达到高亮的效果。 以下是一个示例代码: ``` <template> <div> <input type="text" v-model="searchText" @input="highlightText" placeholder="请输入搜索关键字"> <div v-html="highlightedContent"></div> </div> </template> <script> export default { data() { return { searchText: '', content: '这是一段需要搜索的内容,其中包含关键字 Vue高亮。' } }, computed: { highlightedContent() { const regex = new RegExp(this.searchText, 'gi') return this.content.replace(regex, '<span class="highlight">$&</span>') } }, methods: { highlightText() { // 触发 computed 中的方法 } } } </script> <style> .highlight { color: red; font-weight: bold; } </style> ``` 在这个示例中,我们在 data 中定义了 searchText 和 content 两个变量,其中 content 是需要搜索的内容。在模板中使用 input 元素来渲染搜索框,并使用 v-model 将输入的内容绑定到 searchText 上,在 input 事件中触发 highlightText 方法。使用 v-html 指令将 computed 中返回的内容渲染为 HTML。在 computed 中定义了一个方法 highlightedContent,使用正则表达式将匹配到的内容用 span 标签包裹。最后在样式中定义了高亮的样式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值