搜索需求:

搜索框为空,默认展示下面的搜索历史,隐藏搜索列表
如果用户输入搜索内容:
有搜索结果展示:搜索结果,
没有搜索结果展示:暂无搜索内容
点击搜索列表的选项,自动填充到搜索框
具体代码如下:

封装防抖截流函数:


/**
 * 
 * @param {*} fn 
 * @param {*} delay 
 * 
 * 节流函数throttle:在delay时间内,时间只触发一次
 * 防抖函数:在delay时间后,输入完成后多长时间才会触发一次;如果在输入时间内,用户再次输入就会重新计时
 */
 
function throttle (fn, delay) {
  var t = null,
    begin = new Date().getTime();
  return function () {
    var _self = this,
      args = arguments,
      cur = new Date().getTime();

    clearTimeout(t);

    if (cur - begin >= delay) {
      fn.apply(_self, args);
      begin = cur;
    } else {
      t = setTimeout(function () {
        fn.apply(_self, args)
      }, delay);
    }
  }
}

export {
  throttle
}

搜索功能

<template>
  <div class="wrap">
    <input
      v-model="input_value"
      type="text"
      placeholder="请搜索"
      @keyup="searchAction"
      ref="input"
    />
    <ul v-show="isShow">
      <li
        v-for="(item, index) of searchRes"
        :key="index"
        @click="choose(item.name)"
      >
        <div>{{ item.name }}</div>
      </li>
    </ul>
    <div v-show="!isShow && !isClick && input_value.length == 0">搜索历史</div>
    <div v-if="searchRes.length == 0 && input_value.length > 0">
      暂无搜索结果
    </div>
  </div>
</template>

<script type="text/javascript">

import { throttle } from '@/libs/utils';

export default {
  data () {
    return {
      searchRes: [], // 搜索的结果
      CourseData: [
          {name: '北京1'},
          {name: '上海1'},
          {name: '广州2'},
          {name: '深圳3'}
      ],  // 搜索联想,这里可以请求接口拿数据
      input_value: '', // 输入框的值
      isClick: false, // 是否点击搜索项
      isShow: false  // 是否展示数据列表
    }
  },
  methods: {
    // 选择列表选项
    choose (props) {
      this.isClick = true;
      this.isShow = false;
      this.input_value = props
    },
    // 搜索功能:节流函数
    searchAction: throttle(function (e) {

      //拿到当前input输入框输入的值
      this.input_value = this.$refs.input.value;

      //判断展示ul列表,如果输入了就展示没输入就不展示
      this.isClick = this.isShow = this.input_value.length > 0 ? true : false
	  // 搜索的结果
      this.searchRes = this.CourseData.filter((item) => {
        if (item.name.includes(e.target.value)) {
          return item;
        }
      })
    }, 300)
  }
}
</script>

<style lang="less" scoped>
</style>


原文链接:前端实现模糊查询

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐