vue3 el-table 去除小数 并使用千分号

在 Vue 3 中使用 Element Plus 的 <el-table> 组件时,如果你想在表格的某个列中去除小数并使用千分号来格式化数字,你可以通过以下几种方式实现:

方法 1:使用自定义列模板

你可以通过定义一个自定义的列模板来格式化数字。这种方法允许你完全控制如何显示数据。

复制代码
<template>
  <el-table :data="tableData" style="width: 100%">
    <el-table-column prop="date" label="日期" width="180" />
    <el-table-column label="金额">
      <template #default="scope">
        {{ formatNumber(scope.row.amount) }}
      </template>
    </el-table-column>
  </el-table>
</template>
 
<script setup>
import { ref } from 'vue';
 
const tableData = ref([
  { date: '2023-04-01', amount: 12345.67 },
  { date: '2023-04-02', amount: 98765.43 },
  // 更多数据...
]);
 
function formatNumber(value) {
  if (!value) return '';
  const num = Math.round(value); // 去除小数
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); // 添加千分号
}
</script>

方法 2:使用计算属性或方法格式化数据

如果你希望在数据传递给表格之前就进行格式化,你可以在数据源对象上添加一个计算属性或方法,然后在表格中使用这个属性或方法。

复制代码
<template>
  <el-table :data="formattedTableData" style="width: 100%">
    <el-table-column prop="date" label="日期" width="180" />
    <el-table-column prop="formattedAmount" label="金额" />
  </el-table>
</template>
 
<script setup>
import { computed, ref } from 'vue';
 
const tableData = ref([
  { date: '2023-04-01', amount: 12345.67 },
  { date: '2023-04-02', amount: 98765.43 },
  // 更多数据...
]);
 
const formattedTableData = computed(() => {
  return tableData.value.map(item => ({
    ...item,
    formattedAmount: formatNumber(item.amount)
  }));
});
 
function formatNumber(value) {
  if (!value) return '';
  const num = Math.round(value); // 去除小数
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); // 添加千分号
}
</script>

方法 3:使用过滤器(如果你在使用 Vue 2 或 Vue 3 的 Composition API 但想保持类似 Vue 2 的语法风格)

虽然 Vue 3 不再支持全局过滤器,但你可以通过创建一个函数并直接在模板中调用它来模拟过滤器的行为。上面的方法 1 和方法 2 已经展示了如何在 Vue 3 中实现这一点。如果你确实想保持类似 Vue 2 的语法风格,可以封装一个函数并在模板中使用它。但通常推荐使用计算属性或方法,因为它们在 Vue 3 中更为自然和强大。

以上方法都可以帮助你在 Element Plus 的 <el-table> 中去除小数并使用千分号格式化数字。选择最适合你项目需求的方法。

相关推荐
摘星编程32 分钟前
React Native for OpenHarmony 实战:ImageBackground 背景图片详解
javascript·react native·react.js
摘星编程2 小时前
React Native for OpenHarmony 实战:Alert 警告提示详解
javascript·react native·react.js
Joe5562 小时前
vue2 + antDesign 下拉框限制只能选择2个
服务器·前端·javascript
WHS-_-20222 小时前
Tx and Rx IQ Imbalance Compensation for JCAS in 5G NR
javascript·算法·5g
摘星编程2 小时前
React Native for OpenHarmony 实战:GestureResponderSystem 手势系统详解
javascript·react native·react.js
lili-felicity2 小时前
React Native for OpenHarmony 实战:加载效果的实现详解
javascript·react native·react.js·harmonyos
济6173 小时前
linux 系统移植(第六期)--Uboot移植(5)--bootcmd 和 bootargs 环境变量-- Ubuntu20.04
java·前端·javascript
lili-felicity3 小时前
React Native for OpenHarmony 实战:Easing 动画完全指南
javascript·react native·react.js
持续前行3 小时前
vscode 中找settings.json 配置
前端·javascript·vue.js
JosieBook3 小时前
【Vue】11 Vue技术——Vue 中的事件处理详解
前端·javascript·vue.js