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