[掘金笔记]一个指令解决ElementUI 输入框千分位

125 阅读1分钟

一个指令解决ElementUI 输入框千分位

const namespace = '$THOUSANDTH$'
function focus (e) {
  this.isFocus = true
  e.target.value = e.target.value.replace(/,/g, '')
  console.log('focus', e.target.value)
}
function blur (e) {
  this.isFocus = false
  e.target.value = format(e.target.value)
  console.log('blur', e.target.value)
}
function format(number) {
  return !(number + '').includes('.')
    ? (number + '').replace(/\d{1,3}(?=(\d{3})+$)/g, (match) => {
      return match + ','
    })
    : (number + '').replace(/\d{1,3}(?=(\d{3})+(\.))/g, (match) => {
      return match + ','
    })
}
export default {
  bind (el, binding, vnode) {
    let targetEl = el
    if (el.tagName !== 'INPUT') {
      targetEl = el.querySelector('input')
    }
    if (!targetEl) {
      console.warn('input tag no found !')
      return
    }
    const handers = {
      isFocus: false,
      target: targetEl
    }
    handers.focus = focus.bind(handers)
    handers.blur = blur.bind(handers)
    targetEl.addEventListener('focus', handers.focus)
    targetEl.addEventListener('blur', handers.blur)

    vnode.context.$nextTick(() => {
      targetEl.value = format(targetEl.value)
    })
    el[namespace] = handers
  },
  update (el, binding, vnode) {
    const handers = el[namespace]
    if (handers && !handers.isFocus) {
      const targetEl = handers.target
      vnode.context.$nextTick(() => {
        targetEl.value = format(targetEl.value)
      })
    }
  },
  unbind (el) {
    const handers = el[namespace]
    if (handers) {
      delete el[namespace]
      handers.target.removeEventListener('focus', handers.focus)
      handers.target.removeEventListener('blur', handers.blur)
    }
  }
}

<el-input v-thousandth/>

number类型要特殊弄下。

<el-input :type="type" @focus="type='number'" @blur="type='text'" v-thousandth />