vue注册事件 -防止多次点击

// 注册
let vueAsyncClick = {};
let Helper = {
  getRandomKey() {
    return 'vue-async-' + Math.random().toString().replace(/\D/g, '');
  },
}
// 非异步时间点击等待时长单位ms
let delayTime = 300;
let workSpace = {};
vueAsyncClick.install = function (Vue) {
  Vue.directive('asyncClick', {
    bind: function (el, binding, vNode) {
      let {
        event,
        params
      } = binding.value;
      let key = '';
      if (typeof event !== "function") throw ('asyncClick需要绑定一个事件');
      if (el.hasOwnProperty('vue-async-id')) {
        key = el['vue-async-id'];
      } else {
        key = el['vue-async-id'] = Helper.getRandomKey();
        workSpace[key] = {};
      }
      workSpace[key] = {
        event,
        params
      }
      let isWork = true;
      el.addEventListener('click', async function (e) {
        try {
          if (params === undefined) {
            workSpace[key].params = [e];
          } else {
            workSpace[key].params.push(e);
          }
          let _this = vNode.context;
          if (isWork) {
            isWork = false;
            let type = Object.prototype.toString.call(workSpace[key].event);
            await workSpace[key].event.apply(_this, workSpace[key].params);
            if (['[object AsyncFunction]', '[object Promise]'].includes(type)) {
              isWork = true;
            } else {
              setTimeout(() => {
                isWork = true;
              }, delayTime);
            }
          }
        } catch (error) {}
      });
    },
    update: function (el, binding) {
      var key = el['vue-async-id'];
      let {
        event,
        params
      } = binding.value;
      Object.assign(workSpace[key], {
        event,
        params
      })
    },
    unbind: function (el) {
      var key = el['vue-async-id'];
      var data = workSpace[key];
      el.removeEventListener('click', data.event);
      delete workSpace[key];
    }
  })
}
export default vueAsyncClick;复制代码

mian.js中

import asyncClick from '@common/asyncClick'
Vue.use(asyncClick)复制代码

使用

<el-input v-asyncClick="{event: onBtnClicked}">复制代码



转载于:https://juejin.im/post/5c248a6e51882504bd0e79e5

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值