element el-input小数保留两位小数,整数字符串去空格

 1 <template>
 2   <div>
 3     <el-input v-model="nInput" :placeholder="placeholder" :readonly="readonly" :disabled="disabled" :clearable="clearable" @input="onInputValue()" @blur="salaryChange" />
 4   </div>
 5 </template>
 6 
 7 <script>
 8 export default {
 9   props: {
10     value: {
11       type: [String, Number]
12     },
13     placeholder: {
14       type: String
15     },
16     clearable: {
17       type: Boolean,
18       default: false
19     },
20     disabled: {
21       type: Boolean,
22       default: false
23     },
24     readonly: {
25       type: Boolean,
26       default: false
27     },
28     inputType: {
29       type: Number,
30       default: 99
31     }
32   },
33   data() {
34     return {
35       nInput: null
36     }
37   },
38   watch: {
39     nInput(val, oldVal) {
40       this.$emit('input', val)
41     },
42     value(val, oldVal) {
43       this.nInput = val
44     }
45   },
46   created() {
47     this.nInput = this.value
48   },
49   methods: {
50     //控制只能输入小数点后2位
51     onInputValue() {
52       // console.log(this.inputType)
53       if (this.inputType === 1) {
54         //int正整数类型
55         this.nInput = this.nInput.replace(/[^\d]/g, '') //清除“数字”和“.”以外的字符
56       } else if (this.inputType === 2) {
57         //正小数类型,保留两位小数
58         this.nInput = this.nInput.replace(/[^\d.]/g, '') //清除“数字”和“.”以外的字符
59         this.nInput = this.nInput.replace(/\.{2,}/g, '.') //只保留第一个. 清除多余的
60         this.nInput = this.nInput.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
61         this.nInput = this.nInput.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3') //只能输入两个小数
62         if (this.nInput.indexOf('.') < 0 && this.nInput != '') {
63           //以上已经过滤,此处控制的是如果没有小数点,首位不能为类似于 01、02的金额
64           this.nInput = parseFloat(this.nInput)
65         }
66       } else if (this.inputType === 2) {
67         //字符串类型,所有地方都不能有空格
68         this.nInput = this.nInput.replace(/\s/g, '') //清除空格
69       }
70       else{
71         //字符串类型,前后不能有空格
72         this.nInput = this.nInput.trim() //清除空格
73       }
74     },
75     salaryChange(e) {
76       // 在输入框失去焦点的时候,把value值赋值给v-model绑定变量,使两者保持一致
77       //   console.log('触发重新绑定值')
78       this.nInput = e.target.value
79     }
80   }
81 }
82 </script>
83 
84 <style lang="scss" scoped>
85 </style>

 

posted @ 2021-05-18 16:03  ˉ八月  阅读(738)  评论(0编辑  收藏  举报