1. 程式人生 > 其它 >金額元件(自動格式化金額,逗號分隔)

金額元件(自動格式化金額,逗號分隔)

<template>
  <el-input
    v-model="showValue"
    :name="name"
    :placeholder="placeholder"
    :readonly="readonly"
    @focus="handleFocus"
    @blur="handleBlur"
    @change="handleChange"
    @keydown.native="handleKeydown"
  >
    <i slot="suffix" v-if="isIcon">{{unit}}</i>
  </el-input>
</template>

<script>
/*
* * 用於輸入和顯示金額的元件 * 引數說明: * name: 欄位名 * value: 傳入的值 * decimal: 小數點保留位數 * placeholder: 佔位字元 * readonly: 是否只讀 預設false * 新增click時間 @click.native = "handleClick" * */ import { moneyFormat } from '@/utils/current' export default { name: 'AmountInput', props: { name: { type: String,
default: '' }, value: { type: [String, Number], default: '' }, decimal: { // 小數點位數 type: Number, default: 6 }, placeholder: { type: String, default: '' }, readonly: { type: Boolean, default: false }, isIcon: { type: Boolean,
default: true }, unit: { type: String, default: '元' } }, data() { return { showValue: '', // 展示帶分隔符的值 hiddenValue: '' // 傳入計算的值 } }, watch: { value(val, oldVal) { this.showValue = this.renderAmountFormat(val) this.hiddenValue = val } }, created() { const value = this.value if (value) { this.showValue = this.renderAmountFormat(value) this.hiddenValue = value } }, methods: { renderAmountFormat(value) { if (value) { const _value = value + '' return _value.indexOf(',') < 0 ? moneyFormat(value) : value } }, renderAmountUnFormat(value) { if (value) { let _value = value + '' _value = _value.replace(/,/gi, '') return _value } return value }, handleFocus(event) { this.showValue = this.hiddenValue this.$emit('focus', event) }, handleBlur(event) { const value = this.showValue this.hiddenValue = this.renderAmountUnFormat(value) this.showValue = this.renderAmountFormat(this.hiddenValue) this.$emit('input', this.hiddenValue) this.$nextTick(() => { this.$emit('blur', event) }) }, handleChange(value) { if (value && !/^\d+$|^\d*\.\d+$/g.test(value)) { value = this.hiddenValue } this.showValue = moneyFormat(value) this.hiddenValue = this.renderAmountUnFormat(this.showValue) this.$emit('input', this.hiddenValue) this.$nextTick(() => { this.$emit('change', this.hiddenValue) }) }, handleKeydown(event) { if (this.readonly || this.disabled) { return } const keyCode = window.event ? event.keyCode : event.which if ((keyCode > 95 && keyCode < 106) || (keyCode > 47 && keyCode < 60) || keyCode === 8 || keyCode === 9 || keyCode === 46 || keyCode === 37 || keyCode === 39 || (keyCode === 190 && this.showValue.indexOf('.') < 0)) { // enter } else { event.preventDefault() } } } } </script> <style scoped> </style>