需求:前端实现模糊搜索,前提:
后端接口返回全量数据
- 全局定义变量
// 数组示例
// const tagAll = [{ id: "6", name: "lqx爱好", phone:122233333 },{ id: "6", name: "lqx爱好",phone:122233333 },{ id: "6", name: "lqx爱好",phone:122233333 }]
const state = useReactive({ dataSource: [], deeplist:[] });
- 监听 state.dataSource的变化
useUpdateEffect(() => {
// tagAll 父组件传过来的列表
if (tagAll) {
// 列表中的数据,默认全量数据
state.dataSource = tagAll;
// 深拷贝一份数组
state.deeplist = cloneDeep(tagAll);
}
}, [tagAll]);
- 搜索使用的方法
const handlerSearch = (val: string) => {
const tagList = state.deeplist.filter(
(item: { name: string }) => {
return item.name.includes(val) ||item.phone.includes(val)
},
);
// 如果有值,显示包含val的数组值
if (val) {
state.dataSource = tagList;
} else {
// 否则显示全部数据
state.dataSource = state.deeplist;
}
};
- 页面显示
<Search
allowClear
className="drawer-table-search"
placeholder="姓名/手机号"
onChange={(e) => {
handlerSearch(e.target.value);
}}
/>
<div className="selected-container">
{state.dataSource.length && state.dataSource.map((item,index) => (
<div key={index}>{item.name}</div>
)}
</div>