一、Pinia 简介
Pinia 是 Vue 的最新 状态管理工具,是 Vuex 的替代品。其主要特点和优点如下:
-
提供更简单的 API:
去除了mutations
,简化了状态修改的逻辑。 -
提供组合式风格的 API:
与 Vue 3 的新语法(Composition API)统一。 -
去掉 modules 的概念:
每个 Store 都是一个独立的模块,方便管理。 -
更友好的 TypeScript 支持:
提供可靠的类型推断。
二、定义 Store 的两种方式
Pinia 提供了两种方式来定义 Store:对象配置方式 和 箭头函数方式。以下是两种方式的实现与对比。
(一)对象配置方式
通过配置 state
、getters
和 actions
的方式定义 Store:
import { defineStore } from 'pinia'
// 定义 Store
export const useCounterStore = defineStore('counter', {
// state
state: () => ({
count: 0,
}),
// getters
getters: {
doubleCount: (state) => state.count * 2,
},
// actions
actions: {
increment() {
this.count++
},
},
})
特点:
- 类似 Vuex 的模块化设计,结构清晰。
- 更规范,便于新手学习和使用。
(二)箭头函数方式
使用箭头函数返回状态和方法,与 Vue 3 的组合式 API 风格一致:
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
// 定义 Store
export const useCounterStore = defineStore('counter', () => {
// state
const count = ref(0)
// getters
const doubleCount = computed(() => count.value * 2)
// actions
const increment = () => {
count.value++
}
return {
count, // 状态
doubleCount, // 计算属性
increment // 方法
}
})
补充说明:箭头函数方式细分
-
ref
对应 state:
使用ref
声明响应式变量,用于存储状态。 -
computed
对应 getters:
使用computed
声明衍生属性,动态计算值。 -
普通函数对应 actions:
使用普通函数实现逻辑操作,既支持同步,也支持异步。
特点:
- 灵活自由,适合复杂场景。
- 更贴近 Vue 3 Composition API 的使用习惯。
(三)在组件中使用 Store
import { useCounterStore } from '@/stores/counter'
const counterStore = useCounterStore()
counterStore.increment()
console.log(counterStore.doubleCount)
三、两种方式的对比
定义方式 | 对象配置方式 | 箭头函数方式 |
---|---|---|
定义结构 | 使用 state 、getters 和 actions 字段 | 使用组合式 API,直接返回相关变量 |
学习成本 | 类似 Vuex,逻辑清晰但有结构化限制 | 更自由,贴近 Composition API 风格 |
类型推断支持(TS) | 配置文件较容易推断 | 需要手动声明具体类型 |
适用场景 | 适用于中小型项目,逻辑简单易维护 | 适用于大型项目,代码灵活,复用性高 |
四、pinia总结
- 对象配置方式:规范化,适合简单场景,便于维护。
- 箭头函数方式:灵活自由,贴近 Composition API 风格,适合复杂场景。
五、对比vuex
Vuex 修改状态的流程
-
定义
state
- 在
store
中定义需要管理的状态。
- 在
-
定义
mutations
- 通过
mutations
定义同步的修改方法。 - 只能通过
commit
来触发。
- 通过
-
定义
actions
- 通过
actions
定义异步逻辑。 - 调用
commit
执行mutations
。
- 通过
-
调用流程
- 组件中通过
dispatch
调用actions
。 actions
中通过commit
调用mutations
。mutations
修改state
的值。
- 组件中通过
Pinia 修改状态的流程
-
定义
state
- 在
store
中直接声明状态变量。
- 在
-
定义
actions
- 通过
actions
定义同步或异步逻辑。 - 直接修改
state
的值。
- 通过
-
调用流程
- 组件中直接调用
actions
,完成对state
的修改。
- 组件中直接调用
对比
-
Vuex:
- 必须通过
mutations
修改state
,增加了一层约束。 actions
和mutations
分工明确,适合大型项目的维护。
- 必须通过
-
Pinia:
- 直接通过
actions
修改state
,简化了使用流程。 - 更符合 Vue3 的组合式 API 风格。
- 直接通过