如何在 Vue 应用程序中使用 Pinia 状态管理库?安装 Pinia创建 Store 模块使用 Store

如何使用 Pinia
Pinia 是 Vue 3 的状态管理库,它提供了开箱即用的开发生态系统,以便在 Vue 应用程序中管理状态。
安装
npm install pinia
创建 Store
立即学习“前端免费学习笔记(深入)”;
创建一个 store 模块:
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0
}),
actions: {
increment() {
this.count++
},
decrement() {
this.count--
}
}
})使用 Store
在 Vue 组件中使用 store:
Count: {{ counterStore.count }}
特性
Pinia 提供了以下特性:
- 响应式状态: 跟踪状态变化并自动更新组件。
- 持久化: 可通过提供持久的函数来持久化状态。
- 模块化: 允许将 store 分解为较小的模块,以提高可维护性。
- 热模块替换 (HMR): 在开发过程中允许更新 store 模块,而无需重新加载应用程序。
- 开发生态系统: Pinia 支持 DevTools 扩展、插件和社区工具。










