base-input.js 1.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
import {
  debounce,
  throttle
} from 'uni-shared'
import emitter from './emitter'
import keyboard from './keyboard'

export default {
  name: 'BaseInput',
  mixins: [emitter, keyboard],
  model: {
    prop: 'value',
    event: 'update:value'
  },
  props: {
    value: {
      type: [String, Number],
      default: ''
    }
  },
  data () {
    return {
      valueSync: this._getValueString(this.value)
    }
  },
  watch: {
    valueSync (value) {
      this.$emit('update:value', value)
    }
  },
  created () {
    const valueChange = this.__valueChange = debounce((val, oldVal) => {
      this.valueSync = this._getValueString(val)
    }, 100)
    this.$watch('value', valueChange)
    this.__triggerInput = throttle(($event, detail) => {
      this.$trigger('input', $event, detail)
    }, 100)
    this.$triggerInput = ($event, detail) => {
      this.__valueChange.cancel()
      this.__triggerInput($event, detail)
    }
  },
  beforeDestroy () {
    this.__valueChange.cancel()
    this.__triggerInput.cancel()
  },
  methods: {
    _getValueString (value) {
      return value === null ? '' : String(value)
    }
  }
}