js
复制代码
<template>
<input
type="text"
@input="inputEv"
v-model="search"
placeholder="输入用户昵称"
/>
<h5 style="border-bottom: dashed 1px black" v-for="i in renderList">
{{ i.name }}
</h5>
</template>
<script setup>
import { ref } from "vue";
// 假如这里有很多数据
const data = [
{
name: "abcsjddhfjkfkfedkfdjf",
},
{
name: "dfefea",
},
{
name: "fefefee",
},
{
name: "dddwd",
},
{
name: "dwdwd",
},
{
name: "2233",
},
{
name: "ewe34",
},
{
name: "dwdw",
},
{
name: "343dw",
},
{
name: "2343w",
},
{
name: "343ewd",
},
{
name: "2344wd",
},
{
name: "343edwd",
},
{
name: "343wd",
},
{
name: "e2432ew",
},
{
name: "22ewd",
},
{
name: "ewe243",
},
];
const renderList = ref([]);
const search = ref("");
/**
* input事件触发
*/
const inputEv = _ => renderList.value = filterArr(search.value, data)//开始调用过滤方法
/**
* 数据过滤器
* @param {String} filterStr 过滤的字符串
* @param {Array} arr 查询的数组
* @returns Array 过滤返回的数组
*/
const filterArr = (filterStr, arr) => {
// 若传入空值,返回空数组
if (filterStr === "") return [];
const fliterData = [];
arr.forEach((it) => {
// 正则表达式 -> 相当于 -> /xxxx/.test(it.name) -> xxxx表示动态正则 ↓
const reg = new RegExp(filterStr, "gi");
const res = it.name.match(reg); //开始模糊搜索
// 搜索到,push到fliterData
if (res !== null) fliterData.push(it);
});
// 最后返回过滤的数组
return fliterData;
};
</script>