渲染数据过滤出关键字添加高亮样式及可增加点击事件

适用于小程序的渲染数据过滤出关键字高亮及可点击跳转
复制粘贴就可以看效果了,给自己和有需要的人存着!

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>
    <div id="app">
      <button @click="getNewResult">点击查看关键字高亮</button>
      <div>
        <span v-for="item in newResult" >
          <span v-if="item.isKeyword" @click="goArticleDetail(item.id)" style="color:tomato;">{{item.value}}</span>
          <span v-else>{{item.value}}</span>
        </span>
      </div>
    </div>

    <script>
        new Vue({
          el: '#app',
          data: {
            resultData: [
              { 
                articleId: '01',
                diseaseTypeName: '小程序',
                result: '适用于小程序中' 
              },
              { 
                articleId: '02',
                diseaseTypeName: '过滤',
                result: '渲染数据过滤关键字' 
              },
              { 
                articleId: '03',
                diseaseTypeName: '高亮',
                result: '高亮及可点击跳转'  
              }              
            ],
            newResult: []
          },
          // 在 `methods` 对象中定义方法
          methods: {
            getNewResult: function () {
              var that = this;
              for (let i =0;i<this.resultData.length;i++) {
                let str = that.resultData[i]
                this.hiLight(str.result,str.diseaseTypeName,str.articleId)
              }
            },
            hiLight: function (str,key,id) {
              var that = this
              let idx = str.indexOf(key)
              if (idx !== -1) {
                if (idx == 0) {
                  that.newResult.push({isKeyword: true, value:key, id:id})
                  that.hiLight(str.substr(key.length),key,id)
                  return
                } else if (idx > 0) {
                  that.newResult.push({isKeyword: false, value:str.substring(0, idx), id:id})
                  that.hiLight(str.substr(idx),key,id)
                  return
                }
              } else {
                that.newResult.push({isKeyword: false, value:str, id:id})
              }
              console.log('newResult: ',that.newResult)
            },
            goArticleDetail: function (id) {
              alert(id)
            }
          }
        })
    </script> 
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值