<template>
<div id="app">
<a-input-number
v-model="newMoney"
:formatter="inputNumberF"
:parser="inputNumberP"
:precision="decimalPlaces"
@change="onChange"
/>
</div>
</template>
<script>
export default {
name: 'App',
data() {
return {
// 旧值
oldMoney: null,
// 新的值
newMoney: null,
// 整数位
integralDigits: 6,
// 小数位
decimalPlaces: 2,
// 符号 ¥
symbol: '¥'
}
},
methods: {
inputNumberF(value){
let res = this.regHandel(value)
let val = value.replace(res.reg, res.gs)
if(this.symbol != ''){
return `${this.symbol} ${val}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}else{
return val.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}
},
inputNumberP(value){
let res = this.regHandel(value)
let reg2 = null
if(this.symbol != ''){
reg2 = new RegExp(`${this.symbol}\\s?|(,*)`,'g')
}else{
reg2 = new RegExp('(,*)','g')
}
let val = value.replace(reg2, '')
return val.replace(res.reg, res.gs)
},
regHandel(value) {
let reg = null
let gs = null
let dIndex = value.toString().indexOf('.')
// 点开头处理为 0.
if(dIndex === 0) {
value = '0.'
}else{
// 连续点转为一个点
let dIndex2 = value.toString().indexOf('..')
if(dIndex2 !== -1) {
value = value.replace(/\.\./, '.')
}
}
value = value.replace(/[^0-9.]/g, '')
var arr = value.split(".")
if(arr.length == 2 && arr[1] != ''){
reg = new RegExp(`^(-)*(\\d{0,${this.integralDigits}})\\d*\\.(\\d{0,${this.decimalPlaces}}).*$`);
gs = '$1$2.$3'
}else{
reg = new RegExp(`^(-)*(\\d{0,${this.integralDigits}}).*$`);
if(dIndex != -1){
gs = '$1$2.'
}else{
gs = '$1$2'
}
}
return {reg: reg, gs:gs}
},
onChange(value) {
value = parseFloat(value)
if(this.oldMoney == value){
// 旧值等于新值则返回,不执行下面操作
return;
}
// 更新旧值
this.oldMoney = value
console.log('changed', value);
},
}
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
#app .ant-input-number{
width: 200px;
}
</style>