自定义金额指令(千分位隔开)

/*
 * @Author: your name
 * @Date: 2021-07-02 13:31:43
 * @LastEditTime: 2021-07-02 14:59:15
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \hello-world\src\directives.js
 */
/**
 * @description: 
 * @param {*} money
 * @param {*} len
 * @param {*} separator
 * @return {*}
 * 金额的自定义指令
 */
function moneyFormat (money, len, separator = ',') {
  len = len || 2
  if (!money && money !== 0) return ''
  if (isNaN(+money)) return ''
  if (money === 0 || money === '0') return '0.' + '0'.repeat(len)
  var arr = (money + '').split('.')
  var intStr = arr[0] ? arr[0] : 0
  var floatStr = arr[1] ? arr[1] : 0
  if (floatStr === 0) {
    floatStr = '0'.repeat(len)
  } else {
    floatStr = (+('0.' + floatStr)).toFixed(len).split('.')[1]
  }
  money = (intStr + '.' + floatStr).replace(/(\d{1,3})(?=(?:\d{3})+\.)/g, `$1${separator}`)
  return money
}


export const money = (el, binding) => {
  // 判断是否是input元素
  var els = el.tagName.toLocaleUpperCase() === 'INPUT' ? el : (el.querySelector('input') ? el.querySelector('input') : null)
  if (els) {
    el = els
  } else {
    throw new Error('v-money-format requires 1 input')
  }
  const opt = Object.assign({},{
    thousands: ',',
    precision: 2
    }, binding.value ? binding.value : {})
  const regStr = '/^$*+?.|'
  const inRegStr = regStr.includes(opt.thousands) ? (`\\${opt.thousands}`) : opt.thousands
  const thousandsReg = new RegExp(inRegStr, 'g')
  if (!el.isFocus) {
    el.value = moneyFormat(el.value, opt.precision, opt.thousands)
  }
  el.onfocus = function () {
    el.isFocus = true
    console.log(el.value);
    el.value = el.value.replace(thousandsReg, '')/100
  }
  el.onblur = function () {
    el.isFocus = false
    el.value = moneyFormat(el.value, opt.precision, opt.thousands)
  }
  el.oninput = function () {
    const reg = new RegExp('^\\D*(\\d*(?:\\.\\d{0,' + opt.precision + '})?).*$', 'g')
    el.value = el.value.replace(thousandsReg, '').replace(reg, '$1').replace(/^(0)[^.]/g, '$1')
  }
}
//显示省略号
//v-limit = '3'  今天天...
export const limit = (el,data) =>{
  let str = el.innerText
  if(str.length > data.value){
    el.innerText = str.substring(0,data.value) + '...'
  }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值