Skip to content
On this page

Pinia 基本概念

Pinia 是 Vue.js 的现代状态管理库,提供了一套简洁而强大的 API 来管理应用状态。了解其基本概念对于正确使用 Pinia 至关重要。

Store

Store 是 Pinia 中的核心概念,它是状态的容器。每个 Store 都包含:

  • 状态 (State): 存储响应式数据
  • Getters: 计算派生状态
  • Actions: 修改状态和执行业务逻辑
typescript
import { defineStore } from 'pinia'

export const useMainStore = defineStore('main', {
  // 状态
  state: () => ({
    count: 0,
    name: 'Eduardo',
  }),
  
  // Getters
  getters: {
    doubleCount: (state) => state.count * 2,
  },
  
  // Actions
  actions: {
    increment() {
      this.count++
    },
  },
})

状态 (State)

状态是 Store 的核心部分,它存储了应用的数据。在 Pinia 中,状态是响应式的:

  • 状态会自动转换为响应式对象
  • 修改状态会触发视图更新
  • 状态可以通过 Store 实例直接访问

Getters

Getters 类似于 Vue 组件中的计算属性,它们基于状态计算派生值:

  • Getters 是响应式的
  • 可以接受其他 Getters 作为参数
  • 可以接受参数(但会失去缓存优势)

Actions

Actions 是修改状态的唯一方式(虽然可以直接修改,但不推荐):

  • Actions 可以是同步或异步的
  • Actions 接收 Store 实例作为 this 上下文
  • Actions 可以调用其他 Actions

组合式 API vs 选项式 API

Pinia 支持两种 API 风格:

选项式 API

typescript
export const useOptionsStore = defineStore('options', {
  state: () => ({
    count: 0,
  }),
  getters: {
    doubleCount: (state) => state.count * 2,
  },
  actions: {
    increment() {
      this.count++
    },
  },
})

组合式 API

typescript
export const useCompositionStore = defineStore('composition', () => {
  const count = ref(0)
  const name = ref('Eduardo')

  const doubleCount = computed(() => count.value * 2)

  function increment() {
    count.value++
  }

  return { count, name, doubleCount, increment }
})

使用 Store

在组件中使用 Store:

vue
<template>
  <div>
    <p>Count: {{ store.count }}</p>
    <p>Double: {{ store.doubleCount }}</p>
    <button @click="store.increment">Increment</button>
  </div>
</template>

<script setup>
import { useMainStore } from '@/stores/main'

const store = useMainStore()
</script>

插件系统

Pinia 提供了插件系统来扩展功能:

  • 可以扩展 Store 实例
  • 可以添加新的属性或方法
  • 可以拦截操作

TypeScript 支持

Pinia 提供了出色的 TypeScript 支持:

  • 完全的类型推断
  • 状态、Getters 和 Actions 的类型安全
  • 自动推断返回类型

持久化

Pinia 支持状态持久化,可以将状态保存到本地存储中:

  • 自动保存和恢复状态
  • 可配置的持久化策略
  • 支持选择性持久化

这些基本概念构成了 Pinia 的核心,理解它们有助于更好地使用 Pinia 进行状态管理。