我做的功能是根据关键词搜索,关键词在内容中高亮
我的这个方法是将关键词放入一个数组中,然后通过forEach去循环关键词数组,然后每次循环再通过for循环去检查每条数据,找到关键词替换并使用span标签包裹
html代码
内容使用v-html展示
<el-table-column prop="VisitRemark" label="内容" min-width="180">
<template slot-scope="scope">
<span v-html="scope.row.VisitRemark" ></span>
</template>
</el-table-column>
<!-- -->
js代码
data() {
return {
//存放关键词
keywords: [],
}
},
methods: {
// 热词搜索
getSearch() {//我两次搜索共用一个方法儿
this.keywords=[];//每次搜索先清空关键词数组
//再将搜索的关键词push进去(input是我第一次搜索时的关键词)
this.keywords.push(this.input);
//判断列表中的的关键字输入框是否有值,有值再push进去(如果你只有一个关键词就把这个if判断去掉)
if (this.VisitKey) {
this.keywords.push(this.VisitKey);
}
//然后请求接口
this.$ajax(this.$BaseUrl +"asdfasdf","",(msg) => {
this.tableData1 = msg.rows;//这是我的列表
this.replaceArr(this.keywords);//调用替换关键词的方法儿,将关键词数组传过去
},() => {},"get");
},
// 多关键词搜索
replaceArr (keywords) {
//这个方法儿中将tableData1换成自己的界面列表用的字段,VisitRemark这个是你的关键词在列表的哪个字段里面,其他的不需要改
let arr = this.tableData1;
keywords.forEach((keywordItem, keywordIndex) => {//循环关键词
for (let index = 0; index < arr.length; index++) {//循环列表,找出关键词并替换
arr[index].VisitRemark = arr[index].VisitRemark.replace(keywordItem,`<span style="color: #d45802;">${keywordItem}</span>`);
}
})
}