vue中格式化金额组件
尤雨溪git下载,这里是引入
const digitsRE = /(\d{3})(?=\d)/g
export function currency(value, currency, decimals) {
value = parseFloat(value)
if (!isFinite(value) || (!value && value !== 0)) return ''
currency = currency != null ? currency : '$'
decimals = decimals != null ? decimals : 2
var stringified = Math.abs(value).toFixed(decimals)
var _int = decimals ?
stringified.slice(0, -1 - decimals) :
stringified
var i = _int.length % 3
var head = i > 0 ?
(_int.slice(0, i) + (_int.length > 3 ? ',' : '')) :
''
var _float = decimals ?
stringified.slice(-1 - decimals) :
''
var sign = value < 0 ? '-' : ''
return sign + currency + head +
_int.slice(i).replace(digitsRE, '$1,') +
_float
}
使用
导入js文件,因为是根据函数名导出,所以,导入需要进行解构
import { currency } from "@/util/currency";
export default {
.........
// 局部过滤器
filters: {
currency: currency,
},
}
格式化组件使用
<div class="item-total">
<span>{{totalPrice | currency('$')}}</span>
</div>