我们注册成全局组件方便全局el-table-column使用
1、在unils文件夹下创建一个thousands.js
// 不带插槽的
export function stateFormat(row, column) {
let num = Number(row[column["property"]]);
let n = 2;
let symbol = ",";
if(typeof num!=='number')throw new TypeError('num参数应该是一个number类型');
if(n<0)throw new Error('参数n不应该小于0');
var hasDot=parseInt(num)!=num;//这里检测num是否为小数,true表示小数
var m=(n!=undefined&&n!=null)?n:1;
num=m==0?num.toFixed(m)+'.':hasDot?(n?num.toFixed(n):num):num.toFixed(m);
symbol=symbol||',';
num=num.toString().replace(/(\d)(?=(\d{3})+\.)/g,function(match, p1,p2) {
return p1 + symbol;
});
if(n==0||(!hasDot&&!n)){//如果n为0或者传入的num是整数并且没有指定整数的保留位数,则去掉前面操作中的小数位
num=num.substring(0,num.indexOf('.'));
}
return num;
}
//带插槽的
export function handleScopeFormat(num,n=2,symbol) {
// 保证为number类型
num = Number(num)
if(typeof num!=='number')throw new TypeError('num参数应该是一个number类型');
if(n<0)throw new Error('参数n不应该小于0');
var hasDot=parseInt(num)!=num;//这里检测num是否为小数,true表示小数
var m=(n!=undefined&&n!=null)?n:1;
num=m==0?num.toFixed(m)+'.':hasDot?(n?num.toFixed(n):num):num.toFixed(m);
symbol=symbol||',';
num=num.toString().replace(/(\d)(?=(\d{3})+\.)/g,function(match, p1,p2) {
return p1 + symbol;
});
if(n==0||(!hasDot&&!n)){//如果n为0或者传入的num是整数并且没有指定整数的保留位数,则去掉前面操作中的小数位
num=num.substring(0,num.indexOf('.'));
}
return num;
}
2、在main.js里引入
import {stateFormat,handleScopeFormat} from '@/utils/thousands.js'
Vue.prototype.stateFormat = stateFormat
Vue.prototype.handleScopeFormat = handleScopeFormat
3、快活的使用
//不带插槽的
<el-table-column prop="inPlaceAmt" align="center" :formatter="stateFormat" label="资金1" show-overflow-tooltip />
//带插槽的
<el-table-column align="center" label="资金2" >
<template slot-scope="scope">
{{handleScopeFormat(scope.row.inPlaceAmt - scope.row.allocationAmt)}}
</template>
</el-table-column>
这篇博客介绍了如何在Vue项目中创建全局组件,用于格式化表格数据,包括不带插槽和带插槽的两种情况。通过在unils文件夹下创建thousands.js,导出两个格式化函数stateFormat和handleScopeFormat,然后在main.js中引入并挂载到Vue原型上。这样,在全局范围内,可以便捷地在el-table-column中使用这些格式化函数,例如在表格列定义中设置formatter属性或在插槽内调用,实现了数字的千位分隔和精度控制。
1192

被折叠的 条评论
为什么被折叠?



