数据检索

前端数据检索

第三方库使用

Fuse.js

1
$ npm install fuse.js
Copied!
在 TypeScript 中,我们可以准备如下的数据:
1
// Requires --esModuleInterop compiler flag!
2
// import * as Fuse with '--allowSyntheticDefaultImport'
3
// or import Fuse = require('fuse.js') with neither
4
import Fuse from 'fuse.js';
5
6
type SimpleBookFuse = {
7
title: string;
8
author: {
9
firstName: string;
10
lastName: string;
11
};
12
tags: string[];
13
};
14
15
const books: SimpleBookFuse[] = [
16
{
17
title: "Old Man's War",
18
author: {
19
firstName: 'John',
20
lastName: 'Scalzi'
21
},
22
tags: ['fiction']
23
},
24
{
25
title: 'The Lock Artist',
26
author: {
27
firstName: 'Steve',
28
lastName: 'Hamilton'
29
},
30
tags: ['thriller']
31
}
32
];
Copied!
然后自定义 Fuse 实例以进行检索:
1
const options: Fuse.FuseOptions<SimpleBookFuse> = {
2
keys: ['author', 'tags']
3
};
4
const fuse = new Fuse(books, options);
5
6
const results = fuse.search('tion');
7
8
[{
9
"title": "The Lock Artist",
10
"author": {
11
"tags": [{
12
"value": "English"
13
}]
14
}
15
}]
16
17
// IDE's will show full IntelliSense support
18
// for example when using
19
results[0].ti... => suggested to expand to title
Copied!
Last modified 2yr ago