element el-input小数保留两位小数,整数字符串去空格
element el-input小数保留两位小数,整数字符串去空格
<template> <div> <el-input v-model="nInput" :placeholder="placeholder" :readonly="readonly" :disabled="disabled" :clearable="clearable" @input="onInputValue()" @blur="salaryChange" /> </div></template>
<script>export default { props:{ value:{ type:[String,Number] }, placeholder:{ type:String }, clearable:{ type:Boolean, default:false }, disabled:{ type:Boolean, default:false }, readonly:{ type:Boolean, default:false }, inputType:{ type:Number, default:99 }, }, data() { return { nInput: null } }, watch: { nInput(val, oldVal) { this.$emit('input', val) } }, created() { this.nInput = this.value }, methods: { //控制只能输入小数点后2位 onInputValue() { console.log(this.inputType) if(this.inputType===1){//int正整数类型 this.nInput = this.nInput.replace(/[^\d]/g,''); //清除“数字”和“.”以外的字符 }else if(this.inputType===2){//正小数类型,保留两位小数 this.nInput = this.nInput.replace(/[^\d.]/g, ""); //清除“数字”和“.”以外的字符 this.nInput = this.nInput.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的 this.nInput = this.nInput.replace(".", "$#$").replace(/\./g, "").replace("$#$", "."); this.nInput = this.nInput.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数 if (this.nInput.indexOf(".") < 0 && this.nInput != "") { //以上已经过滤,此处控制的是如果没有小数点,首位不能为类似于 01、02的金额 this.nInput = parseFloat(this.nInput); } }else{//字符串类型,前后不能有空格 this.nInput = this.nInput.replace(/\s/g,''); //清除空格 } }, salaryChange(e) { // 在输入框失去焦点的时候,把value值赋值给v-model绑定变量,使两者保持一致 // console.log('触发重新绑定值') this.nInput = e.target.value } }}</script>
<style lang="scss" scoped></style>
来源
https://www.cnblogs.com/HCXiao/p/14781398.html