使用自定义指令directive如何修改v-model绑定的键值对

2021-07-08 10:17:21 浏览数 (2)

主要语句 vnode.elm.dispatchEvent(new CustomEvent('input'));

代码语言:javascript复制
/**
 * Created by liweiliang 406320591@QQ.com on 2021/01/26 23:04.
 */
import pattern from '@/utils/pattern'

let amountCheck = function (vnode, binding, el) {
  // console.log(el, vnode, binding)
  let reopenState = binding.modifiers.reopen;
  if (!reopenState && !pattern.twoDecimal.test(el.target.value)) {
    vnode.context.$message.error('输入错误,已重置成最后一次输入正确的值')
    el.target.value = el.target.oldValue;
    vnode.elm.dispatchEvent(new CustomEvent('input'));
  } else if (reopenState && !pattern.twoDecimalReopen.test(el.target.value)) {
    vnode.context.$message.error('输入错误,已重置成最后一次输入正确的值')
    el.target.value = el.target.oldValue;
    vnode.elm.dispatchEvent(new CustomEvent('input'));
  }
}
export default {
  directiveName: 'amounts',
  bind (el, binding, vnode, oldVnode) {
    // console.log(el, binding, vnode, oldVnode)
    if (el.nodeName != 'INPUT') return
    el.addEventListener('blur', amountCheck.bind(this, vnode, binding))
  },
  componentUpdated (el, binding, vnode, oldVnode) {
    console.log(binding.name, 'value', binding.value, 'oldValue', binding.oldValue)
    console.log(pattern)
    if (binding.modifiers.reopen) {
      if (pattern.twoDecimalReopen.test(binding.value)) {
        el.oldValue = binding.value
      } else if (pattern.twoDecimalReopen.test(binding.oldValue)) {
        el.oldValue = binding.oldValue
      }
    } else if (pattern.twoDecimal.test(binding.value)) {
      el.oldValue = binding.value
    } else if (pattern.twoDecimal.test(binding.oldValue)) {
      el.oldValue = binding.oldValue
    }
  },
  unbind (el, binding, vnode, oldVnode) {
    el.removeEventListener('blur', amountCheck.bind(this, vnode))
  }
};

0 人点赞