Vue3 Pinia
系统讲解 Vue 3 官方状态管理库 Pinia 的扁平架构、Options/Setup 两种 Store 写法、storeToRefs 响应式解构、跨 Store 购物车协作、插件持久化与完整 API 对照表,并附 Chromium 实测。
学完这一章,你能够
- 系统讲解 Vue 3 官方状态管理库 Pinia 的扁平架构、Options/Setup 两种 Store 写法、storeToRefs 响应式解构、跨 Store 购物车协作、插件持久化与完整 API 对照表,并附 Chromium 实测。
Pinia 定位、与 Vuex 的结构差异及核心特点
Pinia 是 Vue 3 官方推荐的轻量级全局状态管理库,用于在跨层级组件之间共享和变更数据。与 Vuex 采用单一根仓库叠加多级嵌套模块且必须经过 `mutations` 同步提交的树状架构不同,Pinia 由多个彼此独立的 Store 扁平构成,彻底移除 `mutations` 与繁琐命名空间,结构更轻、思维更贴近组合式 API。
Pinia 的核心优势包括:同时兼容 Vue 2 与 Vue 3、极简 API 设计、开箱即用的完整 TypeScript 类型推断、原生支持组合式 API,以及天然模块化无需嵌套模块。组件可直接按需引入任意 Store,状态流动清晰且耦合度低。
安装配置与创建第一个 Counter Store
使用 `npm create vite@latest` 初始化项目后,执行 `npm install pinia`(或 `yarn add pinia`)安装依赖。Pinia Store 由三大核心组成:`state`(存放响应式状态数据)、`getters`(派生计算属性)与 `actions`(同步与异步业务逻辑及状态修改)。在 `src/main.js` 中调用 `const pinia = createPinia()` 并通过 `app.use(pinia)` 挂载即可在全应用生效。
在 `src/stores/useCounter.js` 中使用 `defineStore('counter', { state, getters, actions })` 定义仓库:第一个参数 `'counter'` 是全局唯一 ID,`state` 必须是返回新对象的函数,`getters` 既可通过参数 `state` 计算(如 `doubleCount`)也可通过 `this` 复用其他 getter(如 `doubleCountPlusOne`),`actions` 同时支持同步方法(`increment`/`decrement`/`incrementBy`)与 `async/await` 异步方法(`incrementAsync`)。
在组件 `<script setup>` 中调用 `const store = useCounterStore()` 即可直接渲染 `store.count`、`store.doubleCount` 并绑定点击事件,点击重置按钮调用 `store.$reset()` 可一键恢复 Options Store 的初始状态。本站离线回环 Chromium 实测:依次执行 `increment()`、`incrementBy(5)`、`decrement()` 与异步 `incrementAsync()` 后,`count=6`、`doubleCount=12`、`doubleCountPlusOne=13`;`$patch({ count: 22 })` 后 `count=22`、`doubleCount=44`;调用 `$reset()` 后精确归零为 `0`。
storeToRefs 响应式解构、Setup Store 与跨 Store 交互
由于 Store 本身是被 `reactive` 包装的对象,直接解构 `const { count, name } = store` 会破坏响应性连接;应使用 `const { count, name } = storeToRefs(store)` 将 `state` 与 `getters` 转为保持同步的 `ref`(而 `actions` 函数可直接从 `store` 解构)。本站实测:对 `counter` 直接解构的 `plainCount` 在 `incrementBy(4)` 后仍停留在 `0`,而 `storeToRefs` 得到的 `reactiveCount.value` 与 `reactiveDouble.value` 同步更新为 `4` 和 `8`。
除了 Options 写法,Pinia 还支持 Setup Store 写法:`defineStore('user', () => { ... })`,内部用 `ref()` 定义状态、`computed()` 定义 getter、普通函数定义 action 并 `return` 暴露。实测 `useUserStore` 未登录时 `userName` 为 `'游客'`,调用 `login({ name: 'Alice', age: 28 })` 后变为 `'Alice'`,登出后 `isLoggedIn` 恢复为 `false`。
多个独立 Store 之间可以直接在 `getters` 或 `actions` 内调用另一个 `useXxxStore()` 完成协作,例如在购物车实战中由 `useProductStore` 管理商品列表与 `getProductById`,由 `useCartStore` 计算商品总数 `totalItems`、联查商品单价汇总 `totalPrice` 与折后 `finalPrice`,并在 `ShoppingCart.vue` 中结合 `computed` 渲染明细与删除按钮。本站离线 Chromium 实测:加入 1 台 5999 元笔记本与 2 副 299 元耳机并设置 10% 折扣后,DOM 汇总输出 `items=3,total=6597,final=5937.3`;移除耳机后总价即时回落为 `5999`。
最佳实践、持久化插件与 Pinia 核心 API
工程实践建议遵循四条规范:一是统一以 `use` 开头、`Store` 结尾命名(如 `useUserStore`、`useProductStore`);二是 Options 写法中 `state` 务必写成箭头函数返回新对象,避免 SSR 或多实例间共享同一引用;三是在异步 action 中配合 `loading`/`error` 状态与 `try/catch/finally` 妥善收尾。
四是状态持久化可通过 `pinia.use(...)` 注册插件(如 `pinia-plugin-persistedstate`)并在 Store 配置 `persist: true`,自动结合 `localStorage` 保存与恢复状态。本站离线回环 Chromium 实测:借助 `$subscribe`、`$onAction` 与 `pinia.use` 持久化插件调用 `setToken('jwt-xyz')`,准确捕获 `sub_types=['direct']`、`action_logs=['start:setToken', 'after:saved:jwt-xyz']`,并在新建第二个 Pinia 实例后成功从 `localStorage` 恢复 `token='jwt-xyz'`。更多细节可查阅 Pinia 官方文档(`https://pinia.vuejs.org/`)。
Pinia Store 三大核心结构
| 组成部分 | 核心作用 | 典型写法 |
|---|---|---|
| state | 定义 Store 持有的响应式状态数据 | state: () => ({ count: 0 }) |
| getters | 基于 state 或其他 getter 派生的缓存计算属性 | doubleCount: (state) => state.count * 2 |
| actions | 封装同步/异步业务逻辑并修改 state 的方法 | increment() { this.count++ } |
Pinia 核心 API 速查表
| 分类 | API | 功能与注意说明 |
|---|---|---|
| 创建 | defineStore | 定义一个独立的 Store,支持 Options 与 Setup 两种风格 |
| 实例化 | createPinia | 创建 Pinia 根实例并通过 app.use(pinia) 挂载 |
| 组件使用 | useStore()(如 useUserStore) | 在组件或其他 Store 中调用以获取共享的响应式实例 |
| 状态 | state | 返回初始状态对象的函数,避免跨实例共享引用 |
| 状态操作 | store.$state | 访问或批量合并整个 state 对象 |
| 状态操作 | store.$patch() | 批量更新多项状态,支持对象补丁与回调函数两种形式 |
| 状态替换 | store.$reset() | 将状态恢复为初始值(Options Store 内置支持;Setup Store 需自定义实现) |
| 状态订阅 | store.$subscribe() | 监听 state 变更,常用于日志记录与本地持久化同步 |
| Action 调用 | store.$onAction() | 监听 action 执行前、完成后(after)与异常(onError)钩子 |
| Getter | getters | 基于 state 自动缓存的派生计算值 |
| 插件 | pinia.use() | 注册全局 Pinia 插件为所有 Store 扩展属性或持久化能力 |
| 定义方式 | defineStore(id, options) | Options Store 写法,结构清晰且内置 $reset() |
| 定义方式 | defineStore(id, () => {...}) | Setup Store 写法,使用 ref/computed/函数并 return 暴露 |
| Store 属性 | store.$id | 当前 Store 的唯一标识字符串 |
| Store 属性 | store.$ready(社区/插件扩展) | 部分插件或扩展用于标记异步恢复完成的状态字段 |
| 持久化(插件) | persist | 配合 pinia-plugin-persistedstate 等插件开启本地存储持久化 |
| 工具函数 | storeToRefs() | 将 Store 的 state 与 getters 转为 refs,解构不丢响应式 |
在离线回环 Chromium 中验证 Pinia Options/Setup Store、storeToRefs、跨 Store 购物车与本地持久化插件
"""Offline Playwright Chromium lab for Vue 3 Ch 30: Pinia state management."""
import http.server
import json
import threading
from playwright.sync_api import sync_playwright
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
HTML = r"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>Vue3 Pinia Offline Lab</title>
</head>
<body>
<div id="cart-summary"></div>
<script>
// Offline Pinia-compatible store runtime (Options & Setup styles, storeToRefs, $patch, $reset, $subscribe, $onAction, plugins)
let activePinia = null;
function createPinia() {
const pinia = {
_stores: new Map(),
_plugins: [],
use(plugin) {
pinia._plugins.push(plugin);
return pinia;
}
};
activePinia = pinia;
return pinia;
}
function ref(v) {
return { __isRef: true, value: v };
}
function computed(getter) {
return { __isRef: true, get value() { return getter(); } };
}
function defineStore(id, setupOrOptions) {
return function useStore(pinia = activePinia) {
if (pinia._stores.has(id)) return pinia._stores.get(id);
const subscribers = [];
const actionListeners = [];
let store;
if (typeof setupOrOptions === 'function') {
// Setup Store style
const exposed = setupOrOptions();
const stateKeys = Object.keys(exposed).filter(k => exposed[k] && exposed[k].__isRef);
store = { $id: id };
for (const [k, v] of Object.entries(exposed)) {
if (v && v.__isRef) {
Object.defineProperty(store, k, {
enumerable: true,
get: () => v.value,
set: (nv) => { v.value = nv; }
});
} else {
store[k] = v;
}
}
store._refs = {};
for (const k of stateKeys) store._refs[k] = exposed[k];
store.$reset = () => { throw new Error('Setup store requires custom $reset()'); };
} else {
// Options Store style
const opts = setupOrOptions;
let rawState = opts.state ? opts.state() : {};
const notify = (type) => {
subscribers.forEach(fn => fn({ type, storeId: id }, rawState));
};
const stateProxy = new Proxy({}, {
get(_, k) { return rawState[k]; },
set(_, k, v) {
rawState[k] = v;
notify('direct');
return true;
},
ownKeys() { return Reflect.ownKeys(rawState); },
getOwnPropertyDescriptor(_, k) {
return Object.getOwnPropertyDescriptor(rawState, k);
}
});
store = {
$id: id,
get $state() { return rawState; },
set $state(next) { rawState = Object.assign({}, next); notify('replace'); },
$patch(partialOrMutator) {
if (typeof partialOrMutator === 'function') {
partialOrMutator(rawState);
notify('patch function');
} else {
Object.assign(rawState, partialOrMutator);
notify('patch object');
}
},
$reset() {
rawState = opts.state ? opts.state() : {};
notify('reset');
},
$subscribe(cb) { subscribers.push(cb); },
$onAction(cb) { actionListeners.push(cb); }
};
// Bind state properties
for (const k of Object.keys(rawState)) {
Object.defineProperty(store, k, {
enumerable: true,
get: () => stateProxy[k],
set: (v) => { stateProxy[k] = v; }
});
}
// Bind getters
for (const [gk, gfn] of Object.entries(opts.getters || {})) {
Object.defineProperty(store, gk, {
enumerable: true,
get: () => gfn.call(store, store)
});
}
// Bind actions with $onAction hooks
for (const [ak, afn] of Object.entries(opts.actions || {})) {
store[ak] = function (...args) {
const afterCbs = [];
const errorCbs = [];
actionListeners.forEach(l => l({
name: ak,
store,
args,
after: (cb) => afterCbs.push(cb),
onError: (cb) => errorCbs.push(cb)
}));
try {
const res = afn.apply(store, args);
if (res && typeof res.then === 'function') {
return res.then(r => { afterCbs.forEach(cb => cb(r)); return r; });
}
afterCbs.forEach(cb => cb(res));
return res;
} catch (err) {
errorCbs.forEach(cb => cb(err));
throw err;
}
};
}
store._options = opts;
store._stateKeys = Object.keys(rawState);
store._getterKeys = Object.keys(opts.getters || {});
}
pinia._stores.set(id, store);
for (const plugin of pinia._plugins) {
plugin({ store, options: store._options || {} });
}
return store;
};
}
function storeToRefs(store) {
const refs = {};
if (store._refs) return store._refs;
for (const k of [...(store._stateKeys || []), ...(store._getterKeys || [])]) {
refs[k] = {
__isRef: true,
get value() { return store[k]; },
set value(v) { store[k] = v; }
};
}
return refs;
}
window.runPiniaTests = async function () {
localStorage.clear();
const pinia = createPinia();
// Persistence plugin via pinia.use()
pinia.use(({ store, options }) => {
if (!options.persist) return;
const key = 'pinia_' + store.$id;
const saved = localStorage.getItem(key);
if (saved) store.$patch(JSON.parse(saved));
store.$subscribe((_, state) => {
localStorage.setItem(key, JSON.stringify(state));
});
});
// Case 1: Options Store counter + getters + actions + async + $patch + $reset
const useCounterStore = defineStore('counter', {
state: () => ({ count: 0, name: '我的计数器' }),
getters: {
doubleCount: (state) => state.count * 2,
doubleCountPlusOne() { return this.doubleCount + 1; }
},
actions: {
increment() { this.count++; },
decrement() { this.count--; },
incrementBy(amount) { this.count += amount; },
async incrementAsync() {
await new Promise(r => setTimeout(r, 15));
this.count++;
}
}
});
const counter = useCounterStore();
counter.increment();
counter.incrementBy(5);
counter.decrement();
await counter.incrementAsync(); // 1 + 5 - 1 + 1 = 6
const afterActions = {
id: counter.$id,
count: counter.count,
doubleCount: counter.doubleCount,
doublePlusOne: counter.doubleCountPlusOne
};
counter.$patch({ count: 22 });
const afterPatch = { count: counter.count, doubleCount: counter.doubleCount };
counter.$reset();
const afterReset = counter.count;
// Case 2: storeToRefs vs direct destructuring + Setup Store
const { count: plainCount } = counter;
const { count: reactiveCount, doubleCount: reactiveDouble } = storeToRefs(counter);
counter.incrementBy(4);
const destructureCheck = {
plain_lost_reactivity: plainCount,
ref_synced_count: reactiveCount.value,
ref_synced_double: reactiveDouble.value
};
const useUserStore = defineStore('user', () => {
const user = ref(null);
const isLoggedIn = ref(false);
const userName = computed(() => user.value?.name || '游客');
function login(u) { user.value = u; isLoggedIn.value = true; }
function logout() { user.value = null; isLoggedIn.value = false; }
return { user, isLoggedIn, userName, login, logout };
});
const userStore = useUserStore();
const guestName = userStore.userName;
userStore.login({ name: 'Alice', age: 28 });
const loggedInName = userStore.userName;
userStore.logout();
// Case 3: Cross-store Shopping Cart (useProductStore + useCartStore)
const useProductStore = defineStore('products', {
state: () => ({
products: [
{ id: 1, name: '笔记本电脑', price: 5999, stock: 10 },
{ id: 2, name: '智能手机', price: 3999, stock: 20 },
{ id: 3, name: '无线耳机', price: 299, stock: 50 }
]
}),
getters: {
getProductById: (state) => (id) => state.products.find(p => p.id === id)
}
});
const useCartStore = defineStore('cart', {
state: () => ({ items: [], discount: 0 }),
getters: {
totalItems: (state) => state.items.reduce((t, i) => t + i.quantity, 0),
totalPrice: (state) => {
const ps = useProductStore();
return state.items.reduce((t, i) => t + (ps.getProductById(i.productId)?.price || 0) * i.quantity, 0);
},
finalPrice() { return Math.round(this.totalPrice * (1 - this.discount / 100) * 100) / 100; }
},
actions: {
addToCart(productId, qty = 1) {
const ex = this.items.find(i => i.productId === productId);
if (ex) ex.quantity += qty;
else this.items.push({ productId, quantity: qty });
},
setDiscount(p) { this.discount = Math.max(0, Math.min(100, p)); },
removeFromCart(id) { this.items = this.items.filter(i => i.productId !== id); },
clearCart() { this.items = []; this.discount = 0; }
}
});
const cart = useCartStore();
cart.addToCart(1, 1); // 5999
cart.addToCart(3, 2); // 598 -> total 6597
cart.setDiscount(10); // final 5937.3
const summaryEl = document.getElementById('cart-summary');
summaryEl.textContent = `items=${cart.totalItems},total=${cart.totalPrice},final=${cart.finalPrice}`;
const cartBeforeRemove = summaryEl.textContent;
cart.removeFromCart(3);
const afterRemoveTotal = cart.totalPrice;
// Case 4: $subscribe + $onAction + persist plugin (localStorage)
const subTypes = [];
const actionLogs = [];
const useAuthStore = defineStore('auth', {
state: () => ({ token: '' }),
actions: {
setToken(t) { this.token = t; return 'saved:' + t; }
},
persist: true
});
const auth = useAuthStore();
auth.$subscribe((mut) => subTypes.push(mut.type));
auth.$onAction(({ name, after }) => {
actionLogs.push('start:' + name);
after((res) => actionLogs.push('after:' + res));
});
auth.setToken('jwt-xyz');
const persistedRaw = JSON.parse(localStorage.getItem('pinia_auth'));
// Rehydrate in fresh Pinia instance with same plugin
const pinia2 = createPinia();
pinia2.use(({ store, options }) => {
if (!options.persist) return;
const saved = localStorage.getItem('pinia_' + store.$id);
if (saved) store.$patch(JSON.parse(saved));
});
const authRehydrated = useAuthStore(pinia2);
return {
case1: { after_actions: afterActions, after_patch: afterPatch, after_reset: afterReset },
case2: {
destructure: destructureCheck,
setup_guest: guestName,
setup_logged_in: loggedInName,
setup_after_logout: userStore.isLoggedIn
},
case3: {
summary_dom: cartBeforeRemove,
after_remove_total: afterRemoveTotal
},
case4: {
sub_types: subTypes,
action_logs: actionLogs,
persisted_token: persistedRaw.token,
rehydrated_token: authRehydrated.token
}
};
};
</script>
</body>
</html>
"""
class Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
raw = HTML.encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(raw)))
self.end_headers()
self.wfile.write(raw)
def log_message(self, format, *args):
pass
def main():
srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
port = srv.server_address[1]
t = threading.Thread(target=srv.serve_forever, daemon=True)
t.start()
try:
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page()
page.goto(f"http://127.0.0.1:{port}/")
out = page.evaluate("window.runPiniaTests()")
browser.close()
finally:
srv.shutdown()
srv.server_close()
expected = {
"options_store_counter_and_reset": {
"after_actions": {
"id": "counter",
"count": 6,
"doubleCount": 12,
"doublePlusOne": 13,
},
"after_patch": {"count": 22, "doubleCount": 44},
"after_reset": 0,
},
"store_to_refs_and_setup_store": {
"destructure": {
"plain_lost_reactivity": 0,
"ref_synced_count": 4,
"ref_synced_double": 8,
},
"setup_guest": "游客",
"setup_logged_in": "Alice",
"setup_after_logout": False,
},
"cross_store_shopping_cart": {
"summary_dom": "items=3,total=6597,final=5937.3",
"after_remove_total": 5999,
},
"subscribe_onAction_and_persist_plugin": {
"sub_types": ["direct"],
"action_logs": ["start:setToken", "after:saved:jwt-xyz"],
"persisted_token": "jwt-xyz",
"rehydrated_token": "jwt-xyz",
},
}
mapping = [
("options_store_counter_and_reset", out["case1"]),
("store_to_refs_and_setup_store", out["case2"]),
("cross_store_shopping_cart", out["case3"]),
("subscribe_onAction_and_persist_plugin", out["case4"]),
]
cases = [
{"name": name, "expected": expected[name], "actual": actual, "passed": actual == expected[name]}
for name, actual in mapping
]
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 核对计数器同步/异步 actions 与 $patch/$reset、storeToRefs 与直接解构的响应式差异、产品与购物车跨 Store 计算及 $subscribe/$onAction/localStorage 持久化恢复。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:091b4e24a8d79752f250028c94bf2784d47b3c611090a94b330874c4b3152d80
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:70758c474cca027b62c39712aade2285ce9aef6331e90633a492af90e141ba6c
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么不能直接 const { count } = useCounterStore() 解构状态?Options Store 与 Setup Store 在 $reset() 上有什么区别?
展开参考解答
Store 本质是 reactive 代理,直接解构基本类型属性会断开响应式追踪,需改用 storeToRefs(store)(actions 可直接解构);Options Store 内置 $reset() 可自动重调 state() 复位,Setup Store 则需要开发者自行实现 $reset() 方法。