用input以及防抖函数实现搜索功能


1.什么是防抖:

(1.)防抖,顾名思义,防止抖动,以免把一次事件误认为多次,敲键盘就是一个每天都会接触到的防抖操作。
(2.)触发高频事件后n秒内函数只会执行一次,如果n秒内高频事件再次被触发,则重新计算时间。
(3.)把高频事件转变成低频事件,从而提高项目性能,提高用户的体验。

2.具体实现:

1.首先要在js文件中配置一个函数;

export default function debounce1(fn, delay) {
     
    let t = null;
    return function () {
     
        if (t) {
     
            clearTimeout(t);
        }
        t = setTimeout(fn, delay);
    }
}

用input以及防抖函数实现搜索功能_第1张图片

2.其次是给input框加input事件可以时时监听到input中值的变化;(此处运用vant组件库中的搜索框,具体使用请参考vant文档;)

    <div class="searchs">
      <van-search
        v-model="keyword"
        show-action
        placeholder="搜索影片、影院"
        @input="onSearch(keyword)"
      >
        <template #action>
          <div @click="onSearch(keyword)">搜索</div>
        </template>
      </van-search>
    </div>

用input以及防抖函数实现搜索功能_第2张图片

3.最后是请求我们需要的数据;

//引入我们封装好的js文件(根据自己的路径进行更改)
import seach from "../../utils/seach";
//在data中初始化temp函数
  data() {
     
    return {
     
      // 优化搜索框(添加防抖)
      temp: ""
    };
  },
  //调用并激活我们封装的防抖函数
  created() {
     
    this.temp = seach(this.getData, 1000);//这里的1000指的是触发高频事件后一秒内函数只会执行一次,如果一秒内高频事件再次被触发,则重新计算时间(可根据自己的需求进行修改)。
  },
   onSearch() {
     
      this.temp();
    },
   getData() {
     
   //在此函数中做数据的请求以及数据的处理
    console.log("在此函数中进行一系列操作");
    },

用input以及防抖函数实现搜索功能_第3张图片
用input以及防抖函数实现搜索功能_第4张图片

你可能感兴趣的:(vue,vue.js,html5)