useFuse
使用 Fuse.js 的 composable 輕鬆實作模糊搜尋。
來自 Fuse.js 網站
什麼是模糊搜尋?
一般來說,模糊搜尋(更正式的名稱為近似字串比對)是一種尋找與給定模式大致相等的字串(而不是完全相等)的技術。
範例
Roslyn Mitchell 分數索引: 0
Cathleen Matthews 分數索引: 1
Carleton Harrelson 分數索引: 2
Allen Moores 分數索引: 3
John Washington 分數索引: 4
Brooke Colton 分數索引: 5
Mary Rennold 分數索引: 6
Nanny Field 分數索引: 7
Chasity Michael 分數索引: 8
Oakley Giles 分數索引: 9
Johanna Shepherd 分數索引: 10
Maybelle Wilkie 分數索引: 11
Dawson Rowntree 分數索引: 12
Manley Pond 分數索引: 13
Lula Sawyer 分數索引: 14
Hudson Hext 分數索引: 15
Alden Senior 分數索引: 16
Tory Hyland 分數索引: 17
Constance Josephs 分數索引: 18
Larry Kinsley 分數索引: 19
安裝 Fuse.js 作為同層級依賴
NPM
bash
npm install fuse.js@^7
Yarn
bash
yarn add fuse.js
用法
ts
import { useFuse } from '@vueuse/integrations/useFuse'
import { shallowRef } from 'vue'
const data = [
'John Smith',
'John Doe',
'Jane Doe',
'Phillip Green',
'Peter Brown',
]
const input = shallowRef('Jhon D')
const { results } = useFuse(input, data)
/*
* Results:
*
* { "item": "John Doe", "index": 1 }
* { "item": "John Smith", "index": 0 }
* { "item": "Jane Doe", "index": 2 }
*
*/
類型宣告
顯示類型宣告
typescript
export type FuseOptions<T> = IFuseOptions<T>
export interface UseFuseOptions<T> {
fuseOptions?: FuseOptions<T>
resultLimit?: number
matchAllWhenSearchEmpty?: boolean
}
export declare function useFuse<DataItem>(
search: MaybeRefOrGetter<string>,
data: MaybeRefOrGetter<DataItem[]>,
options?: MaybeRefOrGetter<UseFuseOptions<DataItem>>,
): {
fuse: Ref<
{
search: <R = DataItem>(
pattern: string | Expression,
options?: FuseSearchOptions,
) => FuseResult<R>[]
setCollection: (
docs: readonly DataItem[],
index?: FuseIndex<DataItem> | undefined,
) => void
add: (doc: DataItem) => void
remove: (predicate: (doc: DataItem, idx: number) => boolean) => DataItem[]
removeAt: (idx: number) => void
getIndex: () => FuseIndex<DataItem>
},
| Fuse<DataItem>
| {
search: <R = DataItem>(
pattern: string | Expression,
options?: FuseSearchOptions,
) => FuseResult<R>[]
setCollection: (
docs: readonly DataItem[],
index?: FuseIndex<DataItem> | undefined,
) => void
add: (doc: DataItem) => void
remove: (
predicate: (doc: DataItem, idx: number) => boolean,
) => DataItem[]
removeAt: (idx: number) => void
getIndex: () => FuseIndex<DataItem>
}
>
results: ComputedRef<FuseResult<DataItem>[]>
}
export type UseFuseReturn = ReturnType<typeof useFuse>
原始碼
貢獻者
更新日誌
v12.8.0
於 2025/3/5v12.3.0
於 2025/1/259f75
- feat(toValue): 棄用 @vueuse/shared 中的 toValue,改用 Vue 原生v12.0.0-beta.1
於 2024/11/21v11.0.0-beta.1
於 2024/6/12v10.0.0-beta.4
於 2023/4/134d757
- feat(types)!: 將 MaybeComputedRef 重新命名為 MaybeRefOrGetter0a72b
- feat(toValue): 將 resolveUnref 重新命名為 toValue