在实现实时搜索功能时,通常会使用输入框的事件监听器来捕获用户的输入变化,并在输入变化时发送搜索请求。为了避免过多的请求导致服务器负担过重,通常会使用“防抖”(debounce)技术来控制请求的频率。
实现步骤
- 监听输入框的变化:使用
input
事件监听器来捕获用户的输入变化。
- 防抖处理:使用防抖函数来限制请求的频率。防抖函数会在用户停止输入一段时间后才发送请求。
- 发送请求:在防抖函数中调用搜索请求。
防抖函数示例
以下是一个简单的防抖函数示例:
1 2 3 4 5 6 7 8
| function debounce(func, wait) { let timeout; return function(...args) { const context = this; clearTimeout(timeout); timeout = setTimeout(() => func.apply(context, args), wait); }; }
|
实现实时搜索
假设你有一个输入框用于搜索患者:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| <script> import { onMount } from 'svelte'; import { patientsStore } from '$lib/stores/patients.svelte';
let searchTerm = '';
// 防抖函数 function debounce(func, wait) { let timeout; return function(...args) { const context = this; clearTimeout(timeout); timeout = setTimeout(() => func.apply(context, args), wait); }; }
// 搜索函数 const searchPatients = debounce(async (term) => { if (term) { // 发送搜索请求 const response = await fetch(`/api/search-patients?query=${term}`); const data = await response.json(); patientsStore.mbglPatients = data; } else { // 清空搜索结果或恢复默认数据 patientsStore.mbglPatients = []; } }, 300); // 300ms 的防抖时间
// 监听输入框变化 function handleInput(event) { searchTerm = event.target.value; searchPatients(searchTerm); } </script>
<input type="text" placeholder="搜索患者..." on:input={handleInput} bind:value={searchTerm} />
|
请求发送间隔
- 防抖时间:通常设置为 300ms 到 500ms 之间。这个时间足够让用户完成输入并减少不必要的请求。
- 考虑用户体验:防抖时间过短可能导致过多请求,过长则可能让用户感到延迟。300ms 是一个常用的折中值。
通过这种方式,你可以实现一个高效的实时搜索功能,既能保证用户体验,又能减少服务器的负担。