美文网首页
vue过滤器,(货币格式化)

vue过滤器,(货币格式化)

作者: 小白的踩坑日常 | 来源:发表于2020-09-24 09:13 被阅读0次

转自
https://blog.csdn.net/weixin_44356804/article/details/104632557?utm_medium=distribute.pc_aggpage_search_result.none-task-blog-2allbaidu_landing_v2~default-1-104632557.nonecase&utm_term=vue%20%E8%B4%A7%E5%B8%81%E6%A0%BC%E5%BC%8F%E5%8C%96%E8%BF%87%E6%BB%A4%E5%99%A8

// 价格金额格式化 (github: vuex --> demo --> shopping-cart -->currency.js)
const digitsRE = /(\d{3})(?=\d)/g
// value: 传入的值; currency: 货币符号; decimals小数位数;
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
}

用法

1, vue

// 导入(main.js)
import {currency} from './util/currency'
Vue.filter("currency",currency);

// 使用(组件里)
<div class="item-price">{{item.salePrice | currency('$')}}</div>

相关文章

网友评论

      本文标题:vue过滤器,(货币格式化)

      本文链接:https://www.haomeiwen.com/subject/gmqzyktx.html