以下是一个基于Vue3的表格合计计算的实例代码,代码中保留了两位小数。
HTML:
<table> <thead> <tr> <th>名称</th> <th>数量</th> <th>单价</th> <th>小计</th> </tr> </thead> <tbody> <tr v-for="(item, index) in items" :key="index"> <td>{{ item.name }}</td> <td> <input type="number" v-model="item.qty" @input="calculateTotal" /> </td> <td> <input type="number" v-model="item.price" @input="calculateTotal" /> </td> <td>{{ item.total.toFixed(2) }}</td> </tr> </tbody> <tfoot> <tr> <td colspan="3" style="text-align: right;">总计:</td> <td>{{ grandTotal.toFixed(2) }}</td> </tr> </tfoot> </table>
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函数作为对象返回,以便在模板中访问。