vue输入框输入数字自动转化成%数据

<template>
  <el-input
    v-model="showValue"
    type="number"
    :name="name"
    :placeholder="placeholder"
    :readonly="readonly"
    :disabled="disabled"
    @focus="handleFocus"
    @blur="handleBlur"
    @change="handleChange"
    clearable
    max-length="100"
  >
    <i v-if="isIcon" slot="suffix">%</i>
  </el-input>
</template>

<script>
/**
 * 用于输入和显示利率的组件
 * 传入的数据为小数点  如0.01
 * 传入进来的输入会自动乘以100   变成1%
 *  参数说明:
 *  name: 字段名
 *  value: 传入的值
 *  decimal: 小数点保留位数
 *  placeholder: 占位字符
 *  readonly: 是否只读 默认false
 *
 */
import Decimal from 'decimal.js'
export default {
  name: 'RateInput',
  props: {
    name: {
      type: String,
      default: ''
    },
    value: {
      type: [String, Number],
      default: ''
    },
    decimal: { // 小数点位数
      type: Number,
      default: 6
    },
    placeholder: {
      type: String,
      default: ''
    },
    readonly: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      showValue: '',
      hiddenValue: '',
      isIcon: true
    }
  },
  watch: {
    value(val, oldVal) {
      if (val > 1 || val < 0) {
        val = oldVal
      }
      this.showValue = this.renderRateFormat(val)
      this.hiddenValue = val
    }
  },
  created() {
    const value = this.value
    if (value) {
      this.showValue = this.renderRateFormat(value)
      this.hiddenValue = value
    }
  },
  methods: {
    renderRateFormat(value) {
      if (value) {
        return Decimal(value).mul(Decimal(100)).toNumber()
      }
    },
    renderUnRateFormat(value) {
      if (value) {
        return Decimal(value).div(Decimal(100)).toNumber()
      }
    },
    handleFocus(event) {
      this.isIcon = false
      this.$emit('focus', event)
    },
    handleBlur(event) {
      this.hiddenValue = this.renderUnRateFormat(this.showValue)
      this.$emit('input', this.hiddenValue)
      this.$nextTick(() => {
        this.$emit('blur', event)
      })
    },
    handleChange(value) {
      this.isIcon = true
      this.hiddenValue = this.renderUnRateFormat(value)
      this.$emit('input', this.hiddenValue)
      this.$nextTick(() => {
        this.$emit('change', this.hiddenValue)
      })
    }
  }
}
</script>

<style scoped>

</style>

 

posted @ 2022-05-07 10:22  Stitchhhhh  阅读(2022)  评论(0编辑  收藏  举报