Vue【原创】千位符输入框(不仅只是过滤器哦)

发布时间 2023-08-24 10:56:58作者: Binyy_Wuhan

最近和一个做金融的朋友讨论到千位符输入的问题,后来一想貌似自己项目中也会经常碰到金额数字这种输入框,要么自己做一个吧。

首先肯定要有一个正则表达式,也就是过滤器的方案里面常用的正则:

1 filters: {
2         _toThousandFilter(str, that) {
3             return that._toNormal(str).replace(/(^|\s)\d+/g, m => m.replace(/(?=(?!\b)(\d{3})+$)/g, ','));
4         }
5     }

 

这个是基于el-input做的拓展,换其他的或者甚至原生的思路都一样,无非是要自己包装一个关于千位符的双向绑定,我这里都是做插件的形式封装,你也可以直接引用组件即可。

 1 <template>
 2     <el-input 
 3         v-bind:value="value | _toThousandFilter(this)" 
 4         v-on:input="input" 
 5         :clearable="clearable" 
 6         :disabled="disabled"
 7         @blur="_dispatchComponentEvent($event, 'blur')"
 8         @change="_dispatchComponentEvent($event, 'change')"
 9         @focus="_dispatchComponentEvent($event, 'focus')"
10         @clear="_dispatchComponentEvent($event, 'clear')"/>
11 </template>
12 <script>
13 export default {
14     name: 'LiloThounsandInput',
15     props: {
16         value: {
17             type: [String, Number],
18             default: ''
19         },
20         clearable: {
21             type: Boolean,
22             default: false
23         },
24         disabled: {
25             type: Boolean,
26             default: false
27         },
28          placeholder: {
29              type: String,
30              default: ''
31          }
32     },
33     filters: {
34         _toThousandFilter(str, that) {
35             return that._toNormal(str).replace(/(^|\s)\d+/g, m => m.replace(/(?=(?!\b)(\d{3})+$)/g, ','));
36         }
37     },
38     methods: {
39         _toNormal(str) {
40             return str.toString().split(',').join('');
41         },
42         input(val) {
43             const result = this._toNormal(val);
44             this.$emit('input', result);
45         },
46         _dispatchComponentEvent(event, eventType) {
47             this.$emit(eventType, event);
48         }
49     }
50 };
51 </script>
52 
53 <style></style>

 

欢迎各路大佬指导、提问~