Web前端之路

js实现模糊搜索(vue组件)

2020-07-14  本文已影响0人  喆哲

平时的搜索功能都是基于后台交互,拿数据就好。前几日碰到了需要使用本地数据匹配模糊搜索的功能,重新封了一个vue小组件以作参考

1.HTML和数据制造

<template>
    <div>
        <van-search 
            shape="round" 
            placeholder="请输入搜索关键词" 
            :clearable='true'
            show-action
            @input="inputSearch"
            v-model="dataList"
            :autofocus='true'>
        </van-search>
        <van-cell :title="v" v-for="(v, x) in showSearchList" :key="x" icon="contact" />
    </div>
</template>

<script>
export default {
    name: 'fuzzySearch',
    data() {
        return {
            dataList: '',
            showSearchList: [],
            searchData: [],
            valueSearch: [
                {name: '小黑', number: '324545'},
                {name: '小蓝', number: '538254'},
                {name: '小紫', number: '213713'},
                {name: '小绿', number: '423545'},
                {name: '小白', number: '643408'},
                {name: '小灰', number: '139234'},
                {name: '小红', number: '320112'},
                {name: '小黄', number: '980231'},
                {name: '小青', number: '454329'},
            ]
        }
    },
    // 进入就分解数据
    created() {
       this.addressDataRemould()
    },

2.组件关键字数组集合

addressDataRemould () {
    for (let x = 0; x < this.valueSearch.length; x++) {
        // 组建关键字数组
        this.searchData.push([this.valueSearch[x].name + this.valueSearch[x].number])
     }
 },

3.组件关键字数组集合

// 搜索
 inputSearch () {
     if (this.dataList === '') {
         this.showSearchList = []
          return
      }
     this.showSearchList = []
     let itReg = new RegExp(this.dataList) // 获取搜索输入框里的数据正则
     for (let v = 0; v < this.searchData.length; v++) {            
       if (this.searchData[v][0].match(itReg)) {
           this.showSearchList.push(this.searchData[v][0]) // 搜索成功的数据
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读