04 全局状态管理的原理

vvEcho 2026-03-20 12:10:10
Categories: Tags:

在 Vue 项目中,全局状态管理通常通过 Pinia 实现。
我会将全局共享的数据,比如用户信息、权限、以及核心业务数据放到 store 中管理,通过 actions 统一修改状态,保证数据的可控性。

在设计上,会按业务拆分 store,比如 userStore、orderStore、marketStore 等,提高可维护性。

同时结合异步 actions 处理接口请求,并通过持久化插件保证关键数据在刷新后不丢失

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import { defineStore } from 'pinia'

export const useOrderStore = defineStore('order', {
state: () => ({
orderList: [],
currentSymbol: 'BTC/USDT'
}),

getters: {
// 当前交易对订单
currentOrders(state) {
return state.orderList.filter(
(o) => o.symbol === state.currentSymbol
)
}
},

actions: {
setSymbol(symbol) {
this.currentSymbol = symbol
},

// 下单
createOrder(order) {
this.orderList.unshift({
...order,
id: Date.now()
})
},

// 删除订单
cancelOrder(id) {
this.orderList = this.orderList.filter(
(o) => o.id !== id
)
}
}
})

// 使用
const orderStore = useOrderStore()

orderStore.setSymbol('ETH/USDT')

orderStore.createOrder({
symbol: 'ETH/USDT',
price: 2000,
amount: 1
})

console.log(orderStore.currentOrders)