1.表单中的金额的输入框里面的数据千分位转换,失去焦点转化为千分位格式,获取焦点变回正常格式
可以自定义到小数点后几位
自定义指令;
// 注册全局指令
Vue.directive('thousandSeparator', {
inserted(el, vDir, vNode,binding) {
let content
el.addEventListener('focusout', (event) => {
// 此处会在 el-input 的 @change 后执行
standard(event)
})
function standard(event) {
const e = event || window.event
content = parseFloat(e.target.value)
let contnerplay=content.toString().replace(/[^0-9.]/g,'')
const toFixed=vDir.value.toFixed
e.target.value=contnerplay?comdify(content.toString(),toFixed):0
}
const comdify=function(s,n){
if (s === '' || s === null || s === undefined || isNaN(Number(s))) {
return s;
}
s = Number(s) ? Number(s) : s;
n = (n >= 0 && n <= 20) ? n : 2;
s = parseFloat(s).toFixed(n);
let [integerPart, decimalPart] = s.split(".");
integerPart = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
decimalPart = (n > 0) ? `.${decimalPart}` : '';
return `${integerPart}${decimalPart}`;
}
const delcommafy = function(num) {
if (!num) return num
num = num.toString()
num = num.replace(/,/gi, '')
return num
}
el.addEventListener('focusin', (event) => {
const e = event || window.event
e.target.value=e.target.value?delcommafy(e.target.value):content?content:''
})
},
})
使用方式; toFixed 表示保留小数点后几位
el-input v-model="form.Plan_Settlement_Amount" class="input" v-thousand-Separator="{toFixed:2}"/>
注意:进行千分位转换后,数据会变成String类型,但是后端需要的是Number类型。所以在把数据传给后端时需要转换数据类型。同理在数据回显时也需要将返回是Number数据类型转换为千分位形式的String类型
转换的方式:
//千分位格式化:10000转为10,000.00
export const comdify=(s,n)=>{
if (s === '' || s === null || s === undefined || isNaN(Number(s))) {
return s;
}
s = Number(s) ? Number(s) : s;
n = (n >= 0 && n <= 20) ? n : 2;
s = parseFloat(s).toFixed(n);
let [integerPart, decimalPart] = s.split(".");
integerPart = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
decimalPart = (n > 0) ? `.${decimalPart}` : '';
return `${integerPart}${decimalPart}`;
}
//千分位反格式化:10,000.00转为10000.00
export const delcommafy=(s)=>{
if (!num) return num
num = num.toString()
num = num.replace(/,/gi, '')
return num
}
使用方式:
this.$set(this.form, 'Plan_Settlement_Amount', Number(comdify(this.form.Plan_Settlement_Amount)))
this.form.Plan_Settlement_Amount =delcommafy(res.Data.contract.Plan_Settlement_Amount,2)