vue表格合计 计算 保留两位小数

以下是一个基于Vue3的表格合计计算的实例代码,代码中保留了两位小数。

HTML:

名称 数量 单价 小计
{{ item.name }} {{ item.total.toFixed(2) }}
总计: {{ grandTotal.toFixed(2) }}

JavaScript:

import { reactive, computed } from 'vue';

export default {
  setup() {
    const items = reactive([
      { name: '物品1', qty: 1, price: 100, total: 0 },
      { name: '物品2', qty: 2, price: 50, total: 0 },
      { name: '物品3', qty: 3, price: 33.33, total: 0 },
    ]);

    const grandTotal = computed(() => {
      let total = 0;
      items.forEach((item) => {
        total += item.total;
      });
      return total;
    });

    function calculateTotal() {
      items.forEach((item) => {
        item.total = item.qty * item.price;
      });
    }

    calculateTotal();

    return { items, grandTotal, calculateTotal };
  },
};

该代码中使用了Vue3的reactive和computed函数,通过对items数组进行响应式管理,在数量和单价发生变化时自动计算并更新小计,再通过computed对所有物品的小计求和得到总计。在计算小计和总计时使用了toFixed方法保留两位小数。最后,将items、grandTotal和calculateTotal函数作为对象返回,以便在模板中访问。

你可能感兴趣的:(vue.js,elementui,javascript)