输入非数字 失焦后 自动转为0.00
输入整数 失焦后 自动转为 整数.00(例如输入12 自动转为 12.00)
输入整数带多位小数 失焦后 自动转为 只保留两位小数 (例如输入 12.123456 自动转为 12.12)
关键代码: v-model、@blur、v-if 对应的代码
<input type="number" v-model.trim="addCartParams.price" @blur="checkInput" v-if="showInput" placeholder="自定义价格" placeholder-class="input-place" />
这里只记录 失焦事件的处理 和 正则
// 金额输入校验
checkInput() {
if (this.addCartParams.price) {
// 获取当前输入的金额
let _price = this.addCartParams.price;
// 对金额进行正则匹配,过滤掉异常字符并保留两位小数
_price = Number(_price.toString().replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')).toFixed(2);
this.addCartParams.price = _price.toString().replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1');
// 手动定义字段,刷新显示用,默认为true(页面一进来默认显示),失焦时为false,延时刷新显示
this.showInput = false;
setTimeout(() => {
this.showInput = true;
});
}
},
数据结构复杂的 处理
我这里是 遍历生成的商品,实现价格输入框可编辑修改,但是数据结构比较深,数据对象...
<input style="color: red" type="number" v-model.trim="item.price" @blur="checkInput(index)" v-if="showInput" />
这里记录了 层级比较深的数组对象赋值方式
// 金额输入校验
checkInput(index) {
// 获取当前输入的金额
const info = this.formParams.orderGoodsHandselList[index];
// 对金额进行正则匹配,过滤掉异常字符并保留两位小数
info.price = Number(info.price.toString().replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')).toFixed(2);
// 层级比较深的数组对象赋值方式,相当于 this.xxx = xxx
this.$set(this.formParams.orderGoodsHandselList[index], 'price', info.price.toString().replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1'));
// 手动定义字段,刷新显示用,默认为true(页面一进来默认显示),失焦时为false,延时刷新显示
this.showInput = false;
setTimeout(() => {
this.showInput = true;
});
},