pinia getters 通过响应式、缓存方式对 state 数组求和,不修改原始数据,适用于总金额、已选数量等汇总;支持基础求和、条件筛选、参数化动态计算及跨字段加权求和。

Pinia Getters 处理表格统计行数据的求和计算,核心是把原始列表状态作为输入,用响应式、缓存的方式返回聚合结果。它不修改原始数据,只做派生计算,适合做“总金额”“已选数量”“平均分”这类汇总逻辑。
基础写法:直接对 state 数组求和
假设表格数据存在 state 的 items 数组中,每项含 price 和 quantity 字段:
- 定义 getter 时传入 state,用 reduce 累加即可
- 结果自动响应变化:只要 items 或其中任意 item 的 price/quantity 改变,getter 就重新计算
- 无需手动监听,也不用在组件里重复写 sum 逻辑
示例:
getters: {
totalAmount: (state) =>
state.items.reduce((sum, item) => sum + (item.price || 0) * (item.quantity || 0), 0),
totalCount: (state) => state.items.reduce((sum, item) => sum + (item.quantity || 0), 0)
}
带条件的求和:比如只算启用项或某类商品
当需要按规则筛选后再汇总,直接在 reduce 前加 filter:
- 例如只统计 status 为 'active' 的行金额
- 或按 category 分组求和(可配合 Object.groupBy 或手动 reduce)
- filter + reduce 组合清晰、可读性强,且仍保持响应式和缓存
示例:
// 只对启用的商品求和activeTotal: (state) =>
state.items
.filter(item => item.status === 'active')
.reduce((sum, item) => sum + item.price * item.quantity, 0)
支持参数的动态求和:按字段名或条件灵活计算
如果同一张表要按不同列多次求和(如 sum by price / by discount / by tax),可让 getter 返回函数:
- 写法是 getter 返回一个接收参数的函数,例如 (field) => ...
- 注意:这种写法会失去缓存,每次调用都执行,适合低频或参数多变场景
- 避免在模板中高频调用,建议在 setup 中预先计算好再传入
示例:
// 按指定字段名求和sumByField: (state) => (field: string) =>
state.items.reduce((sum, item) => sum + (item[field] || 0), 0)
// 使用:
// const store = useTableStore()
// store.sumByField('price')
跨字段组合求和:比如带权重的加权平均
当求和逻辑涉及多个 state 字段或需引用其他 store 数据,可在 getter 中调用 this 或导入其他 store:
- 用 this 访问当前 store 全部 state 和其他 getter(TypeScript 中需标注返回类型)
- 若需用户等级折扣系数,可 import useUserStore 并在 getter 内调用
- PINIA 自动追踪依赖链,user.level 变化时,相关求和结果也会更新
示例:
// 加权总分 = Σ(score × weight)weightedTotal(): number {
return this.items.reduce(
(sum, item) => sum + (item.score || 0) * (item.weight || 1),
0
);
}










