53 lines
1.1 KiB
TypeScript
53 lines
1.1 KiB
TypeScript
import { ref, watch } from 'vue'
|
|
|
|
export interface UseKeywordSearchOptions {
|
|
/** 输入防抖毫秒,默认 380 */
|
|
debounceMs?: number
|
|
}
|
|
|
|
/**
|
|
* 列表页关键词:随输入防抖触发 search;clearKeyword 立即清空并触发一次检索;flushSearch 立即检索(如回车)。
|
|
*/
|
|
export function useKeywordSearch(search: () => void, options?: UseKeywordSearchOptions) {
|
|
const keyword = ref('')
|
|
const debounceMs = options?.debounceMs ?? 380
|
|
let timer: ReturnType<typeof setTimeout> | null = null
|
|
let suppressWatch = false
|
|
|
|
function cancelTimer() {
|
|
if (timer) {
|
|
clearTimeout(timer)
|
|
timer = null
|
|
}
|
|
}
|
|
|
|
function scheduleSearch() {
|
|
cancelTimer()
|
|
timer = setTimeout(() => {
|
|
timer = null
|
|
search()
|
|
}, debounceMs)
|
|
}
|
|
|
|
watch(keyword, () => {
|
|
if (suppressWatch) return
|
|
scheduleSearch()
|
|
})
|
|
|
|
function clearKeyword() {
|
|
cancelTimer()
|
|
suppressWatch = true
|
|
keyword.value = ''
|
|
suppressWatch = false
|
|
search()
|
|
}
|
|
|
|
/** 跳过防抖立即检索(如按下回车) */
|
|
function flushSearch() {
|
|
cancelTimer()
|
|
search()
|
|
}
|
|
|
|
return { keyword, clearKeyword, flushSearch }
|
|
}
|