vue 2.x 在组件中使用防抖

1.声明防抖函数

  Debounce(fn, t){
    
    
      let delay = t || 500;
      let timer = null;
      return function () {
    
    
          if (timer) {
    
    
              clearTimeout(timer);
          }
          timer = setTimeout(() => {
    
    
              fn.apply(this, arguments);
          }, delay);
      }
  }

2.引入防抖函数

import {
    
    Debounce} from '@/utils/common.js'

3.使用防抖函数

<template>
  <div class="about">
    <Input @on-change="handlerChange"></Input>
  </div>
</template>
<script>
import {
    
    Debounce} from '@/utils/common.js'
export default {
    
    
 methods:{
    
    
   handlerChange:Debounce(function(val){
    
    //val 为handlerChange函数的参数
     //业务代码
   })
 }
}
</script>

注意:Debounce里面的回调函数不能用箭头函数,因为箭头函数会使内部的this指向methods层的this,导致this没有指向vue实例,也就是表现为this.xxx为undefined了。

猜你喜欢

转载自blog.csdn.net/weixin_44494811/article/details/113043760
今日推荐