vue实现商品列表总价
实现商品列表总价计算
在Vue中实现商品列表总价计算,可以通过计算属性(computed)来动态计算所有商品价格的总和。以下是一个完整的实现示例:
基础数据准备
在Vue组件的data中定义商品列表数据,每个商品包含价格和数量属性:
data() {
return {
products: [
{ id: 1, name: '商品A', price: 100, quantity: 2 },
{ id: 2, name: '商品B', price: 200, quantity: 1 },
{ id: 3, name: '商品C', price: 150, quantity: 3 }
]
}
}
计算总价
使用计算属性计算商品总价,考虑单价和数量的乘积:

computed: {
totalPrice() {
return this.products.reduce((sum, product) => {
return sum + (product.price * product.quantity)
}, 0)
}
}
模板中显示
在模板中直接使用计算属性显示总价:
<div>
<h3>商品列表</h3>
<ul>
<li v-for="product in products" :key="product.id">
{{ product.name }} - 单价: {{ product.price }}元
- 数量: {{ product.quantity }}
- 小计: {{ product.price * product.quantity }}元
</li>
</ul>
<p>总价: {{ totalPrice }}元</p>
</div>
动态更新功能
如果需要支持动态修改数量,可以添加方法并绑定到输入框:

<li v-for="product in products" :key="product.id">
...
<input type="number" v-model.number="product.quantity" min="1">
</li>
格式化显示
可以使用过滤器或方法格式化价格显示:
filters: {
currency(value) {
return '¥' + value.toFixed(2)
}
}
模板中使用:
<p>总价: {{ totalPrice | currency }}</p>
完整组件示例
export default {
data() {
return {
products: [
{ id: 1, name: '商品A', price: 100, quantity: 2 },
{ id: 2, name: '商品B', price: 200, quantity: 1 },
{ id: 3, name: '商品C', price: 150, quantity: 3 }
]
}
},
computed: {
totalPrice() {
return this.products.reduce((sum, product) => {
return sum + (product.price * product.quantity)
}, 0)
}
},
filters: {
currency(value) {
return '¥' + value.toFixed(2)
}
}
}
这种实现方式会自动响应数据变化,当商品数量或价格修改时,总价会实时更新。计算属性的缓存机制确保了性能优化,只有依赖的数据变化时才会重新计算。






