v-auto-disable

作者: pixels | 来源:发表于2018-04-24 20:17 被阅读42次

现在有个场景,需要转账。当点击按钮提交的时候,调用后端接口实现转账,有时候会出现误点击,用户连续点击N次按钮,那么就会发生N比转账。
对于以上场景,解决方法之一就是:在一笔转账请求返回响应结果之前disable按钮,使得后续点击失效,angular对此提供了一个插件ng-auto-disable,在写Vue代码的时候,对应写了一个基于Vue的auto-disable
注意:此处,统一给disable的元素添加了一个classis-disabled样式


import Vue from 'vue'
const EVENT = {
  click: 'click',
  submit: 'submit'
}

/**
 * <button
 *   v-auto-disable="confirm"
 *   @click="confirm">
 *   confirm
 * </button>
 *
 * inform:
 *   confirm() must return a Promise
 *   not only support button, but also for any html labels
 *
 */

const toggleDisable = el => {
  if (el.getAttribute('disabled')) {
    el.removeAttribute('disabled')
    el.classList.remove('is-disabled')
  } else {
    el.setAttribute('disabled', 'disabled')
    el.classList.add('is-disabled')
  }
}

function disableButton (el, flag = true) {
  el.__scheduled = flag
  toggleDisable(el)
  console.log('begin ' + (flag ? 'disable' : 'enable'))
}

function checkBindingValue (val) {
  if (val instanceof Array) {
    let fn = val[0]
    let args = val[1]
    if (!(fn instanceof Function)) {
      console.error('the first element of the array must be a function handle the event')
      return ''
    }
    if (!(args instanceof Array)) {
      console.error('the second element is an array, it is the params of the event handler')
      return ''
    }
    return {
      fn,
      args
    }
  } else if (val instanceof Function) {
    return {
      fn: val,
      args: ''
    }
  }
  console.error('autoDisable must accept a Array or an Function, like v-auto-disable.click="[handleClick, [param1, param2, ..., paramn]]" or v-auto-disable.click="handleClick"')
  return null
}
/**
 * v-auto-disable Accept an Array or a Function
 * when accept an array,the first element is the funtion name of the v-auto-disable event handler and the second element is arguments of the Function
 *    v-auto-disable.click="[handleClick, [param1, param2, ..., paramn]]"
 * when accept a function, it the the v-auto-disable event handler
 *    v-auto-disable.click="handleClick"
 */
Vue.directive('autoDisable', {
  bind (el, binding, vnode) {
    // let fn = binding.value
    let fnObj = checkBindingValue(binding.value)
    if (!fnObj) {
      return
    }
    let { fn, args } = fnObj
    el.__eName = binding.modifiers.submit ? EVENT.submit : (binding.modifiers.click ? EVENT.click : '')
    // let v_listener = vnode.data.on || (vnode.componentInstance && vnode.componentInstance.$listeners)
    // console.log(v_listener)
    if (!el.__eName) {
      console.error('please define the event modified by auto-disable')
    }
    el.__listener = async function () {
      let cb = fn(...args)
      if (!isPromise(cb)) {
        console.error(cb, binding, 'autoDisable must accept a valid Function which return a Promise!')
        return
      }
      if (el.__scheduled) {
        return
      }
      try {
        disableButton(el)
        cb.then(rs => {
          disableButton(el, false)
        })
        .catch(e => {
          disableButton(el, false)
          throw e
        })
      } catch (e) {
        console.error(e.message)
      }
    }
    el.addEventListener(el.__eName, el.__listener, true)
  },
  unbind (el, binding, vnode) {
    el.removeEventListener(el.__eName, el.__listener, true)
  }
})

function isPromise (promise) {
  return promise && (promise.then instanceof Function)
}

此处,可以传入一个函数或者数组
传入数组:v-auto-disable.click="[handler, [param1, param2, ..., paramn]]",第一个参数是处理函数handler,第二个函数是handler的参数。
传入一个函数名v-auto-disable.click="handler"
.click是修饰词,表示在click事件时触发handler。也可以是v-auto-disable.submit

开始的时候,v-auto-disable.click="[handleClick, [param1, param2, ..., paramn]]"是想写成v-auto-disable.click="handleClick(param1, param2, ..., paramn)"的形式,在directive绑定至组件上时候,会计算binding.value的值,handleClick(param1, param2, ..., paramn)就会在directive绑定的时候而不是发生相应事件的时候触发执行。

一些思考,也是本人最初的想法模仿ng-autodisable的方式来构造v-auto-disable,也就是如@click="handleClick(param1, param2, ..., paramn)" v-auto-disable.click=""。首先说一下ng-autodisable的思想是:获取对应事件的handlers --> 使用unbind方法移除监听事件 --> 添加监听事件,监听事件的回调函数首先disable按钮之类的元素,再调用handlers(handlers要求返回promise),在promise被resolve之后,重新enable按钮之类的元素。Vue避免直接操作DOM元素,没有提供unbind之类的方法,所以最后放弃了,也没继续深入研究,有想法的朋友,也欢迎提供更好的解决方案。代码中注释掉的v_listener可以获取到绑定在元素上的事件,比如let clickEvent = v_listener.click

相关文章

  • v-auto-disable

    现在有个场景,需要转账。当点击按钮提交的时候,调用后端接口实现转账,有时候会出现误点击,用户连续点击N次按钮,那么...

网友评论

    本文标题:v-auto-disable

    本文链接:https://www.haomeiwen.com/subject/wxqbqftx.html