使用 npm 或 yarn 安装:
npm install fuse.js
或
yarn add fuse.js
import Fuse from 'fuse.js';
const list = [
{ title: "Old Man's War", author: "John Scalzi" },
{ title: "The Lock Artist", author: "Steve Hamilton" },
];
const options = {
keys: ['title', 'author'],
};
const fuse = new Fuse(list, options);
const result = fuse.search('Old Man');
console.log(result);
Fuse 构造函数:创建一个新的 Fuse 实例。
const fuse = new Fuse(list, options);
list
:搜索的数据列表。options
:配置选项,用于定义搜索行为。search:执行搜索,返回匹配结果。
const result = fuse.search('search term');
search term
:查询字符串,可以是完整词或部分词。setCollection:更新数据列表。
fuse.setCollection(newList);
newList
:新的数据列表。add:向现有数据列表中添加新的条目。
fuse.add(newItem);
newItem
:新的数据条目。remove:移除特定的条目。
fuse.remove(item => item.title === 'title to remove');
predicate
:用于查找要移除条目的条件函数。Fuse.js 提供了许多高级配置选项,可以更细粒度地控制搜索行为,例如设置阈值、指定不同字段的权重、启用/禁用位置敏感性等。
const options = {
isCaseSensitive: false, // 大小写敏感
includeScore: true, // 包含匹配得分
shouldSort: true, // 按得分排序
includeMatches: true, // 包含匹配详情
findAllMatches: false, // 查找所有匹配项
minMatchCharLength: 2, // 最小匹配字符长度
keys: [
{
name: 'title',
weight: 0.7, // 权重
},
{
name: 'author',
weight: 0.3,
},
],
};