elementUi简单实现搜索提词功能

2,501 阅读2分钟

上周又又又又加需求了,好吧,bring it on

先讲需求目标要实现功能

  1. focus的时候要出历史搜索(要存缓存)
  2. 历史搜索下部出现清除缓存按钮
  3. input的时候要根据后台返回出提词

elementui中比较能用的上就是 el-autocomplete 这个组件,但是呢,组件中要添加清除按钮,这个是比较麻烦的。因为,el-autocomplete 这个东西的slot是写弹框的每一项,而不是弹框整体,所以,这里我是把清空缓存的按钮作为一个选项push到提词数组之中的,然后再对该项进行样式处理;其次根据输入匹配提词,用的会是watch检测,而不是input或change事件

先上html部分

<el-autocomplete ref="input1" hide-loading class="inline-input" v-model="search_word" :fetch-suggestions="querySearch" placeholder="请输入内容">
            <template slot-scope="{ item }">
              <div @click.stop="goSearch(item.value)" :class="item.value === '清空历史搜索'?'clearStorage':''">{{ item.value }}</div>
            </template>
            <el-select v-model="selectCato" slot="prepend" placeholder="请选择">
              <el-option :label="item.label" :value="item.value" v-for="(item, index) in selectOptions" :key="index"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="getResult(search_word, selectCato); getCatogary(search_word, selectCato); pagination.current = 1"></el-button>
          <!-- </el-input> -->
          </el-autocomplete>

值得注意的是要为 el-autocomplete 组件设定ref,因为我们不会设置change事件,所以需要手动收起弹框

然后是js部分

querySearch (queryString, cb) {
      let results = null
      // 调用 callback 返回建议列表的数据
      if (!queryString) {
        if (this.OldSearch.length) {
          results = this.OldSearch.map((item, index) => {
            return {value: item, index: index+1}
          })
          results.push({value: '清空历史搜索', index: this.OldSearch.length+1})
        } else {
          results = []
        }
      } else {
        results = this.complete_word
      }
      cb(results)
    },

此处要判断是否已输入过词语,没有则显示缓存词,有则显示提词,按下选词会触发关闭弹框事件

关闭弹框事件

goSearch (word) {
      if (word !== '清空历史搜索') {
        this.search_word = word
        this.$nextTick(() => {
            this.$refs.input1.close()
            this.$refs.input1.$children[0].blur()
            this.$refs.input2.close()
            this.$refs.input2.$children[0].blur()
        }
      } else {
        
        this.delSearchStorage()
        this.$nextTick(() => {
          this.$refs.input1.close()
          this.$refs.input1.$children[0].blur()
          this.$refs.input2.close()
          this.$refs.input2.$children[0].blur()
        })
      }
    },

上成品

希望大家多多点赞,留言,关注!