input输入框 防抖

1 什么是防抖
防抖:当持续触发事件时,一定时间段内没有再触发事件,事件处理函数才会执行一次,如果设定的时间到来之前,又一次触发了事件,就重新开始计时。

为了避免用户在输入过程中,还没输入完,下面搜索框就一直频繁的在搜索,体验很差。

2 防抖解决方案
首先需要把input 的双向绑定v-mode 拆开为 一个value 和一个input事件,在事件里注册一个函数searchData,searchData里获取到input输入内容,再执行搜索函数,代码如下:

<template>
  <div class="box">
    <el-input class="keyword-filter" v-model="params.name" placeholder="请输入关键字进行过滤" @input="debUpdata"
      @keyup.enter.native="keyWordFilter" suffix-icon="el-icon-search"></el-input>
  </div>
</template>
<script>
export default {
  name: "index",
  data() {
    return {
      params: {
        name: ""
      },
      timer: null,
    }
  },
  mounted() {
    this.initTableData()
  },
  methods: {
    this.initTableData(){     
    },
    keyWordFilter() {
      this.initTableData()
    },
    //输入框防抖搜索
    searchData(e) {
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        this.initTableData()//查询表格内容的函数,此处省略
      }, 300);
        //后面数为多少毫秒不变之后执行
    }
  },
}
</script>

所谓防抖,无非就是让数据的变化延迟执行,所以在searchData内定义一个timer,每一次执行函数的时候先清空timer,然后在使用setTimeout 定时一秒之后,在执行搜索函数,就实现了最基础的防抖,主要实现代码效果如下:

 

posted @ 2024-07-18 15:22  front-gl  阅读(11)  评论(0编辑  收藏  举报