computed的核心作用是基于响应式数据自动计算并缓存结果;它通过依赖追踪和缓存机制避免重复计算,比methods更高效,且天然响应式,适用于购物车总价、总件数、是否为空等实时汇总场景。

Vue 的 computed 计算属性,核心作用是基于响应式数据自动计算并缓存结果。它不是普通方法,也不像 data 那样直接存储值,而是像一个“智能的、会监听变化的 getter”。用在购物车汇总这类场景,再合适不过——商品增删、数量改了,总价、总件数立刻更新,且不重复计算。
为什么 computed 比 methods 更适合购物车汇总?
很多人第一反应是写个方法(比如 getTotalPrice())在模板里调用:{{ getTotalPrice() }}。但这样每次渲染都会执行,哪怕数据没变,性能浪费;而 computed 有缓存机制:只要依赖的数据(如 cartItems)没变,就直接返回上次结果,不重新计算。
另外,computed 是响应式的——你不用手动触发更新,Vue 自己知道该什么时候重算。
购物车基础结构:先搭好数据模型
假设你的购物车数据长这样:
立即学习“前端免费学习笔记(深入)”;
审查 Vue 管理后台的变更请求(Vue 2 + Element UI,Vue 3 + Element Plus)。重点关注最小化变更实现、上线风险检查以及回归检查清单生成。
data() {
return {
cartItems: [
{ id: 1, name: 'iPhone', price: 5999, quantity: 2 },
{ id: 2, name: 'AirPods', price: 1299, quantity: 1 },
{ id: 3, name: 'MacBook', price: 12999, quantity: 1 }
]
}
}
这是典型的响应式数组,后续所有计算都基于它。
用 computed 实现三大汇总值
在 computed 选项里定义三个属性:
-
总金额(totalPrice):每项
price × quantity累加 -
总件数(totalQuantity):所有
quantity相加 -
是否为空(isEmpty):判断
cartItems.length === 0
computed: {
totalPrice() {
return this.cartItems.reduce((sum, item) => sum + item.price * item.quantity, 0)
},
totalQuantity() {
return this.cartItems.reduce((sum, item) => sum + item.quantity, 0)
},
isEmpty() {
return this.cartItems.length === 0
}
}
模板中直接使用:{{ totalPrice }} 元、{{ totalQuantity }} 件、去结算 —— 所有值实时响应,零手动干预。
进阶技巧:带 setter 的 computed(可选但实用)
默认 computed 只有 getter。但购物车有时需要「反向操作」,比如点击「清空购物车」按钮,想通过赋值来清空:this.cartItems = []。这时可以给某个 computed 加 setter:
computed: {
cartSummary: {
get() {
return {
total: this.totalPrice,
count: this.totalQuantity
}
},
set(newValue) {
// 比如 newValue 是 { action: 'clear' },就清空 cartItems
if (newValue.action === 'clear') {
this.cartItems = []
}
}
}
}
然后在按钮上:@click="cartSummary = { action: 'clear' }" —— 语义清晰,逻辑集中。

















