Pinia 用 store 管理跨组件状态,支持 state、getters 与 actions。

本节要点

  • defineStore 创建仓库
  • state 返回初始状态
  • actions 修改状态

代码示例

import { defineStore } from "pinia"

export const useCounter = defineStore("counter", {
  state: () => ({ count: 0 }),
  getters: {
    double: (state) => state.count * 2
  },
  actions: {
    increment() {
      this.count++
    }
  }
})