最近封装了一个可以自带format的输入框组件,效果如下:
我所封装的组件代码如下:
<template> <div> <el-input v-model="startValue" @blur="startInput" :maxlength="maxlength"></el-input> <i class="el-icon-minus padding-top-5"></i> <el-input v-model="endValue" @blur="endInput" :maxlength="maxlength"></el-input> </div> </template> <script> export default { name: "input-format-range", props:['startName','endName','maxlength'], data:()=>({ startValue:'', endValue:'' }), methods:{ checkInput({value}){ value=value?parseFloat(value.toString().replace(/[^0-9._-]/g, ''))||0:''; let formattedValue = ''; if (value !== 0 && value !== '') formattedValue = Number(value) .toFixed(2) .replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g,'$&,'); else formattedValue = value; return formattedValue; }, startInput({target}){ this.startValue = this.checkInput(target); this.$emit('checkInput',{startValue:this.startValue, startName:this.startName, endValue:this.endValue, endName:this.endName}); }, endInput({target}){ this.endValue = this.checkInput(target); this.$emit('checkInput',{startValue:this.startValue, startName:this.startName, endValue:this.endValue, endName:this.endName}); } } } </script>
如果传给后台要纯数字类型,你还需要去掉里面的逗号,你可以在main.js里面定义如下函数:
Vue.prototype.splitValue = function (value) { value = value? parseFloat(value.replace(/,/g ,'')) || 0 : ''; return value };
在父组件中就可以愉快的使用了~:
<template> <inputFormatRange @checkInput="checkPrice" :maxlength="9" :startName="'costPriceFrom'" :endName="'costPriceTo'"></inputFormatRange> </template> <script> import inputFormatRange from '@/components/inputFormatRange.vue' export default { name: "price-manage", components:{inputFormatRange}, data:()=>({ getTable:{ costPriceFrom: '', costPriceTo: '' } }), methods:{ checkPrice(obj){ this.getTable[obj.startName] = this.splitValue(obj.startValue); this.getTable[obj.endName] = this.splitValue(obj.endValue); } } } </script>