首页/ 学科题库/ pinia/ 在组件中使用 Getter
pinia 实战教程

在组件中使用 Getter

2026-06-04 约 5 分钟 juanwangdev

在组件中使用 Getter

在组件中使用 Getter是 Pinia 学习中的单个核心知识点,下面直接说明用法。

定义

在组件中使用 Getter是 Pinia 使用中的一个独立知识点,核心作用是:在模板中直接使用getter,掌握在computed中包装getter的使用方式。

语法

常用语法是在 Store 定义或组件调用处完成配置与使用。

JavaScript
export const useCartStore = defineStore('cart', {
  state: () => ({ items: [] }),
  getters: {
    total: (state) => state.items.reduce((sum, item) => sum + item.price, 0)
  }
})

示例

JavaScript
export const useCartStore = defineStore('cart', {
  state: () => ({ items: [] }),
  getters: {
    total: (state) => state.items.reduce((sum, item) => sum + item.price, 0)
  }
})

注意事项

Pinia 不需要 mutation,简单状态可以直接赋值,复杂批量更新优先使用 $patch()。

要点总结

  • 在组件中使用 Getter 只解决当前知识点对应的问题。
  • 优先使用 Pinia 官方 API,避免引入多余封装。
  • 示例代码应保持 Store 简洁、职责清晰。
想在手机上练这篇的配套题目?
使用微信 卷王开发者小程序/App,首页顶部扫一扫识别下方二维码,即可解锁本讲对应真题与错题本。
了解产品 App
← 上一篇 向 Getter 传递参数 下一篇 → 定义 Getter