使用 FlexSearch 实现快速且自动完成的内容搜索

Posted ·4083 Views·2061 Words

GayHub

https://github.com/nextapps-de/flexsearch

Web 最快且最具内存灵活性的全文搜索库,零依赖。

根据文档,FlexSearch 可在 Node.js 或 Web 端使用

 

背景

做 Snapaper 的最初就有想过做搜索功能,但进行各种搜寻研究后并没有找到合适的方案:

比如:js实现页内搜索、爬取原网站搜索结果等...

偶然刷 Github Trend 的时候发现了 FlexSearch,使用简单且高效。刚好在 Web 也提供了支持。

配合 Vue.js 食用更是不亦乐乎 🙂

 

代码

    var open_search = function(){
	    $('#search_div').css({'opacity':'1','z-index':'100'});
    }
    var close_search = function(){
	    $('#search_div').css({'opacity':'0','z-index':'-100'});
    }
    var search = new FlexSearch({
	    encode: "icase",
        tokenize: "full"
    });

    new Vue({
    el: '#search_div',
    data: {
        papers: null,
        cate: cate_get,
        sub: sub_get,
    	searched : [],
    	search_key : null
    },
    mounted() {
        axios.get('url')
        .then(response => {
            this.papers = response.data;
            this.count = response.data.count;
        }).then(()=>{
            for(var i_k=0;i_k<this.count;i_k++){
    			search.add(i_k,this.papers[i_k].name);
    		}
        })
    },
    methods: {
    	search_btn : function(){
    		this.searched = search.search(this.search_key);
    	}
    }
    });

↑ js 部分

 

<div id="search_div" class="search-div">
	<div class="search-div-inner">
        <h2 style="margin: 0px;">Search</h2>
        <p class="sub-title">Search by paper name</p>
		<button onclick="close_search()" class="uk-button uk-button-default close-btn">Close</button>
		<input v-model="search_key" placeholder="Search by paper name" v-on:input="search_btn" class="search-input"/>
        <div v-for="s in searched" class="search-item">
            <a :href="link ? 'https://papers.gceguide.xyz' + papers[s].name : 'https://papers.gceguide.com/'+ cate + '/' + sub + '/' + papers[s].name" target="_blank" class="searc-item-a" v-html="papers[s].name"></a>
        </div>
    </div>
</div>

↑ HTML 部分

 

    .search-div{
        opacity:0;z-index:-100;position: fixed;padding-top: 20vh;top: 0px;width: 100%;height: 100vh;background: rgb(255, 255, 255);overflow-y: auto;
    }
    .search-div-inner{
        width:40%;margin:0 auto
    }
    .sub-title{
        margin: 0px;font-weight: 300;color: #999;margin-bottom: 20px;
    }
    .close-btn{
        float: right;margin-top: -70px;margin-right: -20px;
    }
    .search-input{
        border: 2px solid #eee;padding: 10px 10px;border-radius: 4px;font-size: 1rem;color: #555;margin-bottom: 15px;width:100%
    }
    .search-item{
        padding: 8px 10px;border: 1px solid #eee;width: 100%;margin-bottom:5px
    }
    .search-item-a{
        color: #777;font-weight: 300;text-decoration: none;letter-spacing: 0.5px;
    }

↑ CSS 部分

 

预览

结合 Vue.js 可以实现快速响应的搜索

Comments

Leave a comment to join the discussion