vue金额组件(自动格式化金额,逗号分隔)
<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
// keyCode键盘上键的键码值 if ((keyCode > 95 && keyCode < 106) || (keyCode > 47 && keyCode < 60) || keyCode === 8 || keyCode === 9 || keyCode === 46 || keyCode === 37 || keyCode === 39 || keyCode === 110 || (keyCode === 190 && this.showValue.indexOf('.') < 0)) {
// enter
} else {
event.preventDefault()
}
}
}
}
</script>
<style scoped> </style>