computed核心作用是基于响应式数据派生可缓存的响应值;购物车总价计算是典型应用,相比methods(无缓存)和ref(需手动更新),它自动追踪依赖、按需更新;支持深层响应性与多级依赖链。

Vue3 的 computed 计算属性,核心作用是基于响应式数据派生出新的、可响应的值,且具备缓存机制——只要依赖的数据没变,多次访问不会重复执行函数。购物车金额自动汇总正是它的典型应用场景。
为什么用 computed 而不是 methods 或普通 ref?
购物车总价需要实时响应商品数量、单价的变化。如果用 methods,每次模板中调用都会重新执行;如果用普通 ref,需手动监听所有变化并更新,极易遗漏或出错。而 computed 自动追踪依赖、按需更新、结果可缓存,代码更简洁可靠。
基础写法:从简单数组开始
假设购物车是一个商品对象数组,每个商品含 price(单价)和 count(数量):
const cartItems = ref([
{ id: 1, name: '苹果', price: 5.5, count: 2 },
{ id: 2, name: '牛奶', price: 12.0, count: 1 },
{ id: 3, name: '面包', price: 8.5, count: 3 }
])
<p>const totalPrice = computed(() => {
return cartItems.value.reduce((sum, item) => {
return sum + item.price * item.count
}, 0)
})</p>模板中直接使用:{{ totalPrice }},它会随 cartItems 中任意 price 或 count 变化而自动更新。
立即学习“前端免费学习笔记(深入)”;
进阶技巧:处理深层响应性与异步场景
注意:Vue3 默认只对 ref、reactive 的顶层属性做响应式追踪。如果商品对象来自 reactive,且你修改了 item.count(如 item.count++),computed 依然能正确响应,因为 reactive 对象内部属性变更也会触发依赖更新。
但若你替换整个 cartItems 数组(如 cartItems.value = newArray),computed 同样会响应——因为它依赖的是 cartItems.value 这个响应式引用本身。
常见误区提醒:
- 不要在 computed 函数里做副作用(如发请求、改 DOM),它只用于计算和返回值
- 避免在 computed 中直接修改响应式数据,否则可能引发循环更新
- 如需格式化(如保留两位小数),可在 computed 内部处理:
return Number(sum.toFixed(2))
实战扩展:带折扣与运费的完整逻辑
真实购物车常含优惠券、满减、运费等规则。computed 可组合多个逻辑:
const couponDiscount = ref(5.0)
const shippingFee = ref(8.0)
const isFreeShipping = computed(() => totalPrice.value >= 99)
<p>const finalPrice = computed(() => {
const discount = Math.min(couponDiscount.value, totalPrice.value)
const fee = isFreeShipping.value ? 0 : shippingFee.value
return Number((totalPrice.value - discount + fee).toFixed(2))
})</p>这里 finalPrice 同时依赖 totalPrice(自身是 computed)、couponDiscount、shippingFee 和 isFreeShipping(另一个 computed),Vue 会自动建立完整的响应链。


















