1. 程式人生 > >vue中常用外掛(貨幣、日期)

vue中常用外掛(貨幣、日期)

貨幣外掛:
價格格式化

// https://github.com/vuejs/vuex/blob/dev/examples/shopping-cart/currency.js

const digitsRE = /(\d{3})(?=\d)/g
/**
 * [currency 金額格式化函式]
 * @param  {[type]} value    [傳進來的值]
 * @param  {[type]} currency [貨幣符號]
 * @param  {[type]} decimals [小數位數]
 * @return {[type]}          [description]
 */
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
}

引用(全域性):import {currency} from './util/currency' Vue.filter("currency",currency)
引用(區域性):import {currency} from './util/currency'
// filters:{ // 定義區域性過濾器
// currency:currency // currency.js傳過來的本就是函式
// },
用法(區域性): {{totalPrice | currency('$')}}
用法(全域性): {{totalPrice | currency()}}

日期外掛:

/**
 * Created by jacksoft on 17/4/26.
 */
Date.prototype.Format = function (fmt) {
  var o = {
    "M+": this.getMonth() + 1, //月份
    "d+": this.getDate(), //日
    "h+": this.getHours(), //小時
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    "S": this.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}
module.exports = {};