vue input输入框防抖debounce函数的使用

方法一:

这种方式很简单,但是能实现一样的功能。

<template>
    <div>
        <input class="inputBox" type="text" placeholder="搜索项目名称" v-model="searchValue" @keyup.enter="searchBtn" @input="searchBtn">
    </div>
</template>


<script>
let timers = null;
export default{
 data(){
  return{
    searchValue:''
  }
 }
methods:{
 searchBtn(){
  clearTimeout(timers)
  timers = setTimeout(() => {
   this.getOfferList()//需要防抖的函数
  }, 500);
 },
 }
}
</script>

方法二:

这个方法是vue官网上的做法。

计算属性和侦听器 — Vue.js

<template>
    <div>
        <input class="inputBox" type="text" placeholder="搜索项目名称" v-model="searchValue">
    </div>
<template>

<script>
export default{
 data(){
  return{
    searchValue:''
  }
 }
//监听input输入值变化
watch:{
  searchValue:function(){
    this.debouncedGetAnswer();
  }
},
created(){
  this.debouncedGetAnswer = this.debounce(this.getOfferList, 500);
  //this.getOfferList是你查询数据的函数,也就是需要防抖的函数
},
methods:{
//防抖
 debounce(fn, delay = 500){
      let timer = null;
      return function() {
        if (timer) {
          clearTimeout(timer)
        }
        timer = setTimeout(() => {
          fn.apply(this, arguments)
          timer = null
        }, delay)
      }
    }
}
</script>

方法三:

1.封装一个模块,引入即可,在utils新建一个js文件,名称随便

// 节流
export function _throttle(fn, wait = 500) {
  let last, now
  return function() {
    now = Date.now()
    if (last && now - last < wait) {
      last = now
    } else {
      last = now
      fn.call(this, ...arguments)
    }
  }
}

// 防抖
export function _debounce(fn, wait = 500) {
  let timer
  return function() {
    let context = this
    let args = arguments
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(context, args)
    }, wait)
  }
}

2.在需要的vue文件引入即可使用

import { _throttle, _debounce } from '@/utils/throttle'

 3.在vue文件的使用方法

// 监听搜索框内容的变化,等输入完成才会执行搜索函数=>即防抖
watch: {
    searchValue: _debounce(function() {
      this.page = 1
      this.getJobFairList()
    })
  },


// 搜索,短时间内连续点击搜索按钮只执行一次搜索函数=>即节流
searchBtn: _throttle(function() {
  if (this.searchValue) {
    this.getJobFairList()
  }
}),

方法三是最近才更新的代码,也是最新的代码,建议使用方法三

  • 5
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值