处理金额千分位的一点点思考

现在有一个场景:要处理一下每个页面的金额为千分位并保留两位小数,此时页面又很多的情况下

如果只有一两个页面我们可能会这样写

在每个页面写这么一个方法,然后用这个方法去处理这个数据:

1
<p>{{ toThousands(money) }}</p>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
methods: {
toThousands(num){
if(!num) return '-'
let result = '';
num = Number(num.toString() || 0).toFixed(2);
let numArr = num.toString().split(".");
let preNum = numArr[0];
let lastNum = numArr[1];
while (preNum.length > 3) {
result = ',' + preNum.slice(-3) + result;
preNum = preNum.slice(0, preNum.length - 3);
}
if (preNum) {
result = preNum + result;
}
result = result + "." + lastNum;
return result;
},
}

再者

写一个方法在js文件内:toThousands.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
export function toThousands(num){
if(!num) return '-'
let result = '';
num = Number(num.toString() || 0).toFixed(2);
let numArr = num.toString().split(".");
let preNum = numArr[0];
let lastNum = numArr[1];
while (preNum.length > 3) {
result = ',' + preNum.slice(-3) + result;
preNum = preNum.slice(0, preNum.length - 3);
}
if (preNum) {
result = preNum + result;
}
result = result + "." + lastNum;
return result;
}

然后在页面上,引入方法:

1
import { toThousands } from '@util/toThousands'

处理数据:

1
2
3
4
5
6
7
methods:{
getList(){
// .....请求数据得到result
result.foreach(item=> item.money = toThousands(item.money));
this.dataList = result;
}
}

但是这种写法已经偏离我们的编码基本规范:代码简单、逻辑清晰

再换一种思路

可能会写上一个过滤器:

1.写一个js方法,见上文
2.注册一个过滤器

1
2
3
import { toThousands } from '@util/toThousands'
// 注册过滤器
Vue.filter('toThousands', toThousands)

然后在vue的插值语法上写上这么一行代码:

1
{{ money | toThousands }}

你可以试试这样

1.同样定义一个js文件,见上文
2.在main.js中写上这两行代码:将方法挂载到全局

1
2
import { toThousands } from '@/util/toThousands';
Vue.prototype.toThousands = toThousands;

你就可以在vue插值语法中这样写

1
{{ toThousands(money) }}

仔细看使用过滤器和把方法挂载到全局,写的代码好像是一样多的,那该如何选择呢?

vue3将移除过滤器​

为什么移除过滤器?

大概是功能重复吧

参考vue3移除过滤器

当然还有很多其他的办法,例如使用计算属性computed(我是没实现),现在有一个场景,拿我们的avue项目来说,使用一个插槽处理金额:

1
2
3
<template slot-scope="scope" slot="financeAmount">
{{ toThousands }}
</template>
1
2
3
4
5
computed:{
toThousands(value){
.....❌❌......
}
}

你可能会说avue可以直接使用formatter,对数据进行格式化,这样的结果是不是还是需要每个页面对应的js数据文件里引入方法,格式化,所以并没有提高复用率

更新于

请我喝[茶]~( ̄▽ ̄)~*

Ming Liu 微信支付

微信支付

Ming Liu 支付宝

支付宝

Ming Liu 贝宝

贝宝