策略
- 模块化:将不同模块的状态管理逻辑拆分到各自独立的Pinia store中。例如,创建
productStore
管理商品列表展示相关状态,cartStore
管理购物车状态,orderStore
管理用户订单状态。这样各模块状态职责明确,便于维护和调试。
- 命名规范:对store中的状态、getter、action使用清晰有意义的命名。比如,在
cartStore
中,状态cartItems
表示购物车中的商品项,addItemToCart
作为添加商品到购物车的action。
- 使用Getter进行派生状态计算:对于需要根据现有状态计算得出的状态,使用getter。例如在
cartStore
中,计算购物车商品总价totalPrice
,可以定义一个getter:
const cartStore = defineStore('cart', {
state: () => ({
cartItems: []
}),
getters: {
totalPrice: (state) => state.cartItems.reduce((acc, item) => acc + item.price * item.quantity, 0)
}
})
- Action的事务处理:对于涉及多个状态变化的复杂操作,通过action进行事务处理,保证状态的一致性。例如在购物车中添加商品时,不仅要更新
cartItems
,还可能需要更新库存等,可在addItemToCart
action中完成这些操作。
const cartStore = defineStore('cart', {
state: () => ({
cartItems: [],
// 假设存在库存状态
stock: {}
}),
actions: {
async addItemToCart(product, quantity) {
if (this.stock[product.id] >= quantity) {
const existingItem = this.cartItems.find(item => item.id === product.id);
if (existingItem) {
existingItem.quantity += quantity;
} else {
this.cartItems.push({ ...product, quantity });
}
this.stock[product.id] -= quantity;
} else {
throw new Error('库存不足');
}
}
}
})
- 订阅(subscribe):利用Pinia的订阅功能,监听状态变化并进行相应处理。例如,当购物车商品数量变化时,自动保存购物车数据到本地存储。
const cartStore = defineStore('cart', {
state: () => ({
cartItems: []
}),
actions: {
// 其他action
}
})
const store = cartStore();
store.$subscribe((mutation, state) => {
localStorage.setItem('cart', JSON.stringify(state.cartItems));
})
- 代码拆分与懒加载:对于大型应用,将Pinia store代码拆分,根据需要进行懒加载。比如,用户订单模块可能在用户进入订单页面时才加载
orderStore
,这样可以提高应用的初始加载性能。
关键代码结构和逻辑总结
- Store定义:通过
defineStore
定义各个模块的store,明确state
、getters
、actions
。
- 状态操作:在
actions
中编写复杂状态变化逻辑,利用getters
计算派生状态,保持状态的单一数据源原则。
- 状态监听与处理:通过
$subscribe
订阅状态变化,进行额外处理,如数据持久化等。