Pinia
Pinia 是 Vue 的官方状态管理库,它提供了一个更简单、更类型安全的方式来管理 Vue 应用的全局状态。
1. 基础概念
1.1 Store
Store 是一个保存状态和业务逻辑的实体,在 Pinia 中使用 defineStore() 定义:
import { defineStore } from 'pinia';
// 选项式写法
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0,
name: 'Counter',
}),
getters: {
doubleCount: (state) => state.count * 2,
},
actions: {
increment() {
this.count++;
},
},
});
// 组合式写法
export const useCounterStore = defineStore('counter', () => {
const count = ref(0);
const name = ref('Counter');
const doubleCount = computed(() => count.value * 2);
function increment() {
count.value++;
}
return { count, name, doubleCount, increment };
});
1.2 核心概念
- State: 状态,store 的数据源
- Getters: 计算属性,基于 state 的派生状态
- Actions: 方法,可以包含业务逻辑和异步操作