利用accounting依赖实现vue中金额千分位格式转换和el 您所在的位置:网站首页 vue金额格式化 利用accounting依赖实现vue中金额千分位格式转换和el

利用accounting依赖实现vue中金额千分位格式转换和el

2024-03-16 09:07| 来源: 网络整理| 查看: 265

前提自己要安装一个accounting依赖 我这里用的"accounting": "^0.4.1"版本 1、在components文件夹下新建一个index.js的文件,代码内容如下

import currencyInputComponent from "./CurrencyInput"; const currencyInput = { install:function(Vue){ Vue.component("currency-input",currencyInputComponent) } } export default currencyInput

2、在components文件夹下新建一个CurrencyInput.vue的文件,代码内容如下

* {{name}} import accounting from "accounting"; export default { props: { value: { type: [String, Number], default: 0, desc: "数值", }, symbol: { type: String, default: "", desc: "货币标识符", }, decimal: { type: Number, default: 2, desc: "小数位", }, disabled: { type: Boolean, default: false, desc: "是否禁止", }, name: { type: String, } }, data() { return { focused: false, }; }, created() { }, computed: { formatValue() { if (this.focused) { return this.value ? accounting.unformat(this.value) : ""; } else { if (this.value === 0) { return accounting.formatMoney(this.value, this.symbol, this.decimal); } else if ( this.value === "" || this.value === null || this.value === undefined ) { return ""; } else { return accounting.formatMoney(this.value, this.symbol, this.decimal); } } }, }, watch: { value(val) {if (this.validateEvent) { this.dispatch("ElFormItem", "el.form.change", [val]); } }, }, methods: { updatevalue(value) { var formatvalue = !!value ? accounting.unformat(value) : ""; this.$emit("input", formatvalue); }, onBlur() { this.focused = false; this.$emit("blur"); this.dispatch("ElFormItem", "el.form.blur", [this.value]); }, selectAll(event) { this.focused = true; setTimeout(() => { event.target.select(); }, 0); }, dispatch(componentName, eventName, params) { var parent = this.$parent || this.$root; var name = parent.$options.componentName; while (parent && (!name || name !== componentName)) { parent = parent.$parent; if (parent) { name = parent.$options.componentName; } } if (parent) { parent.$emit.apply(parent, [eventName].concat(params)); } }, }, };

3、使用

二:element的el-table对金额的格式化

moneyFormatter(row, column, cellValue, index) { if(cellValue == null) return 'null' let n = ''; n = String(cellValue); if(!n) return n; let str = n.split('.'); let re = /\d{1,3}(?=(\d{3})+$)/g; let n1 = str[0].replace(re, "$&,"); return str.length > 1 && str[1] ? `${n1}.${str[1]}` : `${n1}.00`; },

三:千分位格式化数字(这是提出给Number了) // 千分位格式化金额

Number.prototype.moneyFormatter = function () { let val = ''; val = this; if (this !== undefined && this !== null && this !== '') { if(val == null) return 'null' let n = ''; n = String(val); if(!n) return n; let str = n.split('.'); let re = /\d{1,3}(?=(\d{3})+$)/g; let n1 = str[0].replace(re, "$&,"); return str.length > 1 && str[1] ? `${n1}.${str[1]}` : `${n1}.00`; } },


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有