源本科技 | 码上会

Vue3 Pinia Getter

2026/04/25
12
0

引言

通过在 Store 中定义 Getter 函数,开发者能够以声明式的方式从 State 中提取复杂的数据,并确保每次 State 变更时,Getter 返回的值都会自动更新。Getter 通常用于计算衍生数据,如过滤列表、计算总和等。

访问 Store 实例

在大多数情况下,Getter 仅依赖于 State 状态。但在某些场景下,Getter 需要调用其他 Getter 来组合计算数据,此时可以通过 this 关键字访问当前 Store 实例。我们基于计数器 Store 扩展 Getter 功能,创建 src/store/counter.ts 状态管理器容器:

import { defineStore } from 'pinia';

export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0
  }),
  getters: {
    // 基础衍生数据:计算 count 的 2 倍值
    doubleCount: (state) => state.count * 2,
    // 组合 Getter:通过 this 访问当前 store,调用其他 Getter 计算结果
    doublePlusOne(): number {
      return this.doubleCount + 1;
    }
  },
  actions: {
    increment() {
      this.count++;
    }
  }
});

在组件中使用 Getter

在 Vue 组件中,结合 storeToRefs 解构 Store 中的 State 和 Getter,保证数据的响应式特性,完整组件代码如下:

<template>
  <h2>解构 Store</h2>
  <div>{{ count }}</div>
  <div>{{ doubleCount }}</div>
  <div>{{ doublePlusOne }}</div>
  <button @click="increment">Increment</button>
</template>

<script setup lang="ts">
import { storeToRefs } from 'pinia';
import { useCounterStore } from '@/store/counter';

const counterStore = useCounterStore();
// 解构 State 和 Getter,保留响应式
const { count, doubleCount, doublePlusOne } = storeToRefs(counterStore);

const increment = () => {
  counterStore.increment();
};
</script>

<style scoped>
button {
  margin: 10px;
  padding: 10px;
  background-color: #4CAF50;
  color: white;
  border: none;
  cursor: pointer;
}

button:hover {
  background-color: #45a049;
}
</style>