目录

模糊搜索

模糊搜索

一、前言

做项目中经常遇到通过搜索框输入内容去查询一些东西,为了更好的用户体验,经常会有模糊查询到需求。对于模糊搜索,我有两种理解:一是不需要输入完整的内容就可以搜索出相关的结果;二是通过输入的内容给用户一个联想提示,类似于百度搜索时的那种效果。二者可以同时做到。对于输入内容就可以将相关结果展示出来,这个主要是靠后台去完成,前端只需要将用户输入的内容作为参数传给后端即可,所以这篇文章主要讲的是联想搜索。

二、组件

以vue+Element UI来实现这个功能

el-autocomplete是专门用来处理模糊搜索的组件,属于el-input范畴

https://i-blog.csdnimg.cn/blog_migrate/066471514a21ee2b04fed9cea7e76dd5.png

<template>
    <div class="_fuzzy_search">
        <h1>模糊搜索</h1>
        <el-autocomplete v-model="input" placeholder="请输入内容" :fetch-suggestions="queryName"></el-autocomplete>
    </div>
</template>

三、方法

	data () {
        return {
            input: '',
            restaurants: []
        }
    },
    methods: {
        loadAll () {
            //这里在实际项目中应该是从后台获取所有的数据
            return [
                { "value": "三全鲜食(北新泾店)", "address": "长宁区新渔路144号" },
                { "value": "Hot honey 首尔炸鸡(仙霞路)", "address": "上海市长宁区淞虹路661号" },
                { "value": "茶芝兰(奶茶,手抓饼)", "address": "上海市普陀区同普路1435号" },
                { "value": "新旺角茶餐厅", "address": "上海市普陀区真北路988号创邑金沙谷6号楼113" },
                { "value": "泷千家(天山西路店)", "address": "天山西路438号" },
                { "value": "胖仙女纸杯蛋糕(上海凌空店)", "address": "上海市长宁区金钟路968号1幢18号楼一层商铺18-101" },
                { "value": "贡茶", "address": "上海市长宁区金钟路633号" },
                { "value": "豪大大香鸡排超级奶爸", "address": "上海市嘉定区曹安公路曹安路1685号" },
                { "value": "茶芝兰(奶茶,手抓饼)", "address": "上海市普陀区同普路1435号" },
                { "value": "十二泷町", "address": "上海市北翟路1444弄81号B幢-107" },
                { "value": "星移浓缩咖啡", "address": "上海市嘉定区新郁路817号" },
                { "value": "CoCo都可(北新泾店)", "address": "上海市长宁区仙霞西路" },
                { "value": "阿姨奶茶/豪大大", "address": "嘉定区曹安路1611号" },
                { "value": "新麦甜四季甜品炸鸡", "address": "嘉定区曹安公路2383弄55号" },
                { "value": "Monica摩托主题咖啡店", "address": "嘉定区江桥镇曹安公路2409号1F,2383弄62号1F" },
                { "value": "浮生若茶(凌空soho店)", "address": "上海长宁区金钟路968号9号楼地下一层" },
                { "value": "NONO JUICE  鲜榨果汁", "address": "上海市长宁区天山西路119号" },
                { "value": "CoCo都可(北新泾店)", "address": "上海市长宁区仙霞西路" },
                { "value": "快乐柠檬(神州智慧店)", "address": "上海市长宁区天山西路567号1层R117号店铺" }
            ]
        },
        queryName (string,cb) {
            var restaurants = this.restaurants
            var result = string?restaurants.filter(this.createInputFilter(string)):restaurants
            cb(result)
        },
        //对数据进行去重
        createInputFilter (string) {
            return (input) => {
                return (input.value.toLowerCase().indexOf(string.toLowerCase()) === 0)
            }
        }
    },
    mounted() {
        this.restaurants = this.loadAll()
    }

四、结果

https://i-blog.csdnimg.cn/blog_migrate/97ff6cd53377fb16fcd5901b3f37c68d.png

https://i-blog.csdnimg.cn/blog_migrate/2ce4926ed95fa324e5f466e4986e1822.png