uni-app 点击事件防抖避免重复操作

在根目录下新建utils文件并创建antiShake.js文件

/**
 * @methods 函数
 * @info 参数
 */
function antiShake(methods, info) {
    
    
    // methods是需要点击后需要执行的函数, info是点击需要传的参数
    let that = this;
   if (that.noClick) {
    
    
        // 第一次点击
        that.noClick= false;
        if(info && info !== '') {
    
    
            // info是执行函数需要传的参数
           methods(info);
       } else {
    
    
           methods();
       }
       setTimeout(()=> {
    
    
           that.noClick= true;
       }, 2000)
   } else {
    
    
       // 这里是重复点击的判断
   }
}

export default {
    
    antiShake}

因为使用的比较多直接全局main.js引入

import utils from './utils/antiShake'
Vue.prototype.$antiShake = utils.antiShake

页面使用

  • 第一种不设置参数
<template>
  <view class="content">
    <button type="primary" @click="$antiShake(login)">防抖</button>
  </view>
</template>

<script>
export default {
    
    
  data() {
    
    
    return {
    
    
		  noClick:true, //按钮防抖设置
    };
  },
  methods: {
    
    
    login() {
    
    
      console.log('1')
    }
  },
};
</script>

第二种设置参数

<template>
  <view class="content">
    <button type="primary" @click="$antiShake(login, 100)">防抖</button>
  </view>
</template>

<script>
export default {
    
    
  data() {
    
    
    return {
    
    
		  noClick:true, //按钮防抖设置
    };
  },
  methods: {
    
    
    login(e) {
    
    
      e // 接收参数
      console.log(e)
    }
  },
};
</script>

猜你喜欢

转载自blog.csdn.net/qq_52099965/article/details/127840088