input.vue 2.88 KB
<template>
  <div class="input-class">
    <div class="wrapper-label" v-if="label">
      <label class="input-label"> {{label}} </label>
      <span class="tip" v-if="showRequired">{{ required ? tip.required : tip.optional}}</span>
      <span class="error" v-if="showError">{{error}}</span>
    </div>
    <slot>
      <input ref="input" :type="type" class="wrapper-input" :placeholder="placeHolder" :value="inputValue"
             @input="onInputChange" @blur="validate" :maxlength="maxLength"/>
    </slot>
  </div>
</template>

<script>
const NUMREG = /^[0-9]+([.]{1}[0-9]+){0,1}$/;

export default {
  name: 'CInput',
  props: {
    value: {
      type: [String, Number],
      default() {
        return '';
      }
    },
    label: {
      type: String,
      default() {
        return '';
      }
    },
    type: {
      type: String,
      default() {
        return '';
      }
    },
    placeHolder: {
      type: String,
      default() {
        return '';
      }
    },
    showRequired: {
      type: Boolean,
      default() {
        return false;
      }
    },
    required: {
      type: Boolean,
      default() {
        return false;
      }
    },
    maxLength: {
      type: Number,
      default() {
        return 100;
      }
    }
  },
  data() {
    return {
      inputValue: this.value,
      tipError: '不能为空',
      numTipError: '只能为数字',
      error: '不能为空',
      showError: false,
      tip: {
        required: '(必填)',
        optional: '(选填)'
      }
    };
  },
  methods: {
    onInputChange() {
      if (this.$refs.input.value.length > this.maxLength) {
        this.$refs.input.value = this.$refs.input.value.slice(0, this.maxLength);
      }

      this.inputValue = this.$refs.input.value;
      this.$emit('input', this.$refs.input.value);
    },
    setShowError(status = true) {
      this.showError = status;
    },
    validate() {
      if (!this.required) {
        return true;
      }

      if (!this.inputValue) {
        this.error = this.tipError;
        this.showError = true;
        return false;
      } else {
        if (this.type === 'number') {
          if (NUMREG.test(this.inputValue)) {
            this.showError = false;
            return true;
          } else {
            this.error = this.numTipError;
            this.showError = true;
            return false;
          }
        } else {
          this.showError = false;
          return true;
        }
      }
    }
  }
};
</script>

<style lang="scss" scoped>
  .input-label {
    font-size: 36px;
    display: inline-block;
    font-weight: bold;
  }

  .wrapper-label {
    margin-bottom: 30px;
  }

  .wrapper-input {
    font-size: 28px;
    width: 100%;
    /*line-height: 1;*/
    line-height: normal;
  }

  .error {
    margin-left: 12px;
    color: #d0021b;
  }

  .tip {
    font-size: 20px;
  }

  ::-webkit-input-placeholder {
    color: #aaa;
  }
</style>