第一次写,写的不好请见谅
我用的是vue和ant-design
<template>
<div>
<a-input placeholder="请输入金额" v-model="money" @change="changeMoney"/>
</div>
</template>
<script>
export default {
name: 'Money',
data() {
return {
money: '',
};
},
methods: {
changeMoney(e) {
let money = e.target.value;
const index = money.indexOf('.');
if (money.substring(0, 1) === '.') { // 第一个不可以为点
money = '';
}
if (money && index > -1) { // 不可存在第二个点
const beforeMoney = money.split('.')[0];
money = `${beforeMoney.substring(0, 7)}.${money.split('.')[1]}`;
}
if (money && index > -1 && money.length - index > 3) { // 点后面只能存在两位数
money = money.substring(0, index + 3);
}
if (money && index === -1) { // 小数点前只可以存在7位数
money = money.substring(0, 7);
}
if (money && money === '00') { // 开头两个0,就去除一个0
money = '0';
}
money = money.replace(/[^\d.]/g, ''); // 清除"数字"和"."以外的字符
this.money = money;
},
},
};
</script>
<style>
</style>