前端实现模糊查询

前端实现模糊查询

搜索需求:

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

具体代码如下:

工具类:


/**
 * 
 * @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>

  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

落花流雨

你的鼓励将是我创作的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值