index.vue 2.8 KB
<template>
  <div class="vux-x-input weui-cell">
    <div class="weui-cell__bd weui-cell__primary">
      <input class="weui-input" style="text-align: center;" type="number" v-on="listeners" v-model="val" ref="input" :placeholder="placeholder" :disabled="disabled" @focus="onFocus">
    </div>
  </div>
</template>

<script type="text/ecmascript-6">
export default {
  mounted () {
    this.updateValue(this.value)
  },
  name: 'vue-pattern-input',
  props: {
    value: {
      required: true,
      default: '',
      type: [Number, String]
    },
    regExp: {
      type: RegExp,
      default: null
    },
    replacement: {
      type: String,
      default: ''
    },
    placeholder: {
      type: String,
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      val: '',
      tmp: ''
    }
  },
  computed: {
    listeners () {
      const listeners = {}

      Object.keys(this.$listeners).forEach(fnName => {
        listeners[fnName] = (e) => {
          let val = e.target.value !== '' ? e.target.value : e.data
          // console.warn(val);
          this.$listeners[fnName](val)
        }
      })

      listeners.input = (e) => {
        let val = e.target.value !== '' ? e.target.value : e.data
        // console.warn(val);
        this.updateValue(val)
      }

      return listeners
    }
  },
  methods: {
    // format the value of input
    formatValue (val) {
      let formattedValue = ''
      // const formattedValue = val.toString().replace(this.regExp, this.replacement)
      val = _.isNull(val) ? '' : val
      if (this.regExp.test(val.toString())) {
        formattedValue = val.toString();
        this.tmp = val.toString()
      } else {
        formattedValue = this.tmp ? this.tmp : ' '
      }

      return formattedValue
    },

    // update the value of input
    updateValue (val) {
      const formattedValue = this.formatValue(val)

      this.val = formattedValue
      this.emitInput(formattedValue)
      this.emitChange(formattedValue)
    },

    // emit input event
    emitInput (val) {
      this.$emit('input', val)
    },

    // emit change event
    emitChange () {
      this.$emit('change', this.val)
    },
    onFocus (e) {
      this.$emit('on-focus', e);
    }
  },
  watch: {
    // watch value prop
    value (val) {
      if (val !== this.val) {
        this.updateValue(val)
      }
    }
  }
}
</script>

<style lang="less">
  .vux-x-input.weui-cell {
    border: 1px solid #eee;
    padding: 0;
    border-radius: .2rem;
  }

  .weui-cell__bd {
    -ms-flex: 1;
    flex: 1;
  }

  .weui-input {
    width: 100%;
    border: 0;
    outline: 0;
    -webkit-appearance: none;
    background-color: transparent;
    font-size: inherit;
    color: inherit;
    height: 1.41176471em;
    line-height: 1.41176471;
  }
</style>