本文共 1110 字,大约阅读时间需要 3 分钟。
在 Vue.js 应用中,使用 Pinia Store 管理状态时,可以通过订阅机制实时获取状态信息。Pinia 提供了 $subscribe 方法,该方法可用于监听状态变更,类似于常见的 watch 组件,但其优势在于订阅仅在状态发生变更后触发一次(如使用函数形式时)。
detached: true 参数实现。export default { setup() { const someStore = useSomeStore(); // 订阅会在组件卸载后自动取消 someStore.$subscribe((mutation, state) => { // mutation.type 包含 mutation 类型信息 // mutation.storeId 对应当前 store 的 ID(如 'cart') // mutation.payload 包含补丁信息(仅适用于 'patch object' 类型) localStorage.setItem('cart', JSON.stringify(state)); }); // 使用 detached: true 保留订阅 someStore.$subscribe((mutation, state) => { localStorage.setItem('cart', JSON.stringify(state)); }, { detached: true }); }}; 通过 Pinia Store 的订阅机制,可以方便地实现状态监听和持久化。合理使用订阅选项(如 detached: true),可提升组件管理的灵活性和性能。
转载地址:http://zhtfk.baihongyu.com/