对列表的数据进行模糊筛选(可选择是否进行显示数据条数筛选)+高亮
演示代码:
方法:
// 模糊查询 高亮匹配
getMachlist() {
// 去除恶意输入代码片段的可能
let value = this.wordage.replace(/<.*?>/gi, "");
// 修改高亮文案
let dataList = [];
// 声明正则校验 (正则表达式,"匹配模式") /gi(全文查找、忽略大小写)
const reg = new RegExp(value, "gi");
// 循环遍历 this.list 使用数据进行渲染 resultList 使用只符合条件的数据
this.list.forEach((item) => {
let obj = {
id: item.id,
title: item.title.replace(
reg,
//筛选出来的文字加样式
(val) => `<span style='color:red'>${val}</span>`
),
};
dataList.push(obj);
});
// 赋值
this.machlist = dataList;
},
详细代码:
<template>
<div class="home">
<h1>筛选文字高亮</h1>
<!-- <div v-html="brightenKeyword(list, text)"></div> -->
---------------------------------------------------------------
<br />
<input
type="text"
@keyup.enter="getMachlist"
v-model="wordage"
placeholder="请输入关键字"
/>
<input type="button" @click="getMachlist" value="确定" />
<div
style=""
v-for="item in machlist"
:key="item.id"
v-html="item.title"
></div>
</div>
</template>
<script>
export default {
name: "AsdHomeView",
data() {
return {
// //全部列表
list: [
{
id: 1,
title: "qwe RTY uio ASD fgh ZXC",
},
{
id: 2,
title: "QWE rty UIO asd ZXC",
},
{
id: 3,
title: "君不见黄河之水天上来,奔流到海不复回。",
},
{
id: 4,
title: "君不见高堂明镜悲白发,朝如青丝暮成雪。",
},
{
id: 5,
title: "人生得意须尽欢,莫使金樽空对月。",
},
{
id: 6,
title: "天生我材必有用,千金散尽还复来。",
},
], //全部列表
machlist: [], // 匹配列表
wordage: "", //搜索框输入的值
};
},
mounted() {
// 打开页面获取数据
this.getMachlist();
},
watch: {
// 文字清空时调用
wordage() {
if (this.wordage === "") {
this.getMachlist();
}
},
},
methods: {
// 模糊查询 高亮匹配
getMachlist() {
// 去除恶意输入代码片段的可能
let value = this.wordage.replace(/<.*?>/gi, "");
// 模糊查询 只保留符合条件的数据
let resultList = [];
this.list.forEach((item) => {
if (
// 英文大小写数据进行判断 toUpperCase 大写 toLowerCase 小写
item.title.indexOf(value.toUpperCase()) > -1 ||
item.title.indexOf(value.toLowerCase()) > -1
) {
resultList.push(item);
}
});
// 修改高亮文案
let dataList = [];
// 声明正则校验 (正则表达式,"匹配模式") /gi(全文查找、忽略大小写)
const reg = new RegExp(value, "gi");
// 循环遍历 this.list 使用数据进行渲染 resultList 使用只符合条件的数据
this.list.forEach((item) => {
let obj = {
id: item.id,
title: item.title.replace(
reg,
//筛选出来的文字加样式
(val) => `<span style='color:red'>${val}</span>`
),
};
dataList.push(obj);
});
// 赋值
this.machlist = dataList;
},
},
};
</script>
<style scoped>
</style>