按钮防抖和Vue中自定义指令防抖

// 防止按钮抖动,思路:获取到本次和上次点击的时间戳,相减小于1000毫秒则return,阻止继续操作
if (new Date().getTime() - this.newTimeStamp < 1000) {
    return this.$message({
     type: 'warning',
     message: '重复点击,请一秒后再试!',
    })
   }

// 代码块

this.newTimeStamp = new Date().getTime()

 Vue中自定义指令防抖,创建一个js文件,代码如下:

import Vue from 'vue'

// 按钮防抖,300毫秒内只触发一次请求
Vue.directive('debounce', {
 inserted: function(el, binding) {
  let timer
  el.addEventListener('click', () => {
   if (timer) {
    clearTimeout(timer)
   }
   timer = setTimeout(() => {
    // 关键点:vue的自定义指令传递的参数binding如果是一个函数,则通过binding.value()来执行
    binding.value()
   }, 300)
  })
 },
})

然后在main.js中引入:

 

 使用:

v-debounce="export_data"

 

posted @ 2021-03-31 09:58  yw3692582  阅读(460)  评论(0)    收藏  举报