"""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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/vue3-pinia-lab/explore-pinia.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-pinia.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联48章) · 含当前章节或实例 · mbskycom202612a801.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a827.zip