npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@bams-app/store

v0.2.5

Published

`@bams-app/store` 提供业务系统通用 Pinia store,并内置跨浏览器 tab 的 store 状态同步插件。

Readme

@bams-app/store

@bams-app/store 提供业务系统通用 Pinia store,并内置跨浏览器 tab 的 store 状态同步插件。

多 tab 同步插件

同步插件用于解决同一个应用在多个浏览器 tab 中打开时,Pinia store 数据不能实时同步的问题。

典型场景:

  • A tab 打开或关闭页签后,B/C tab 的页签列表同步更新。
  • A tab 切换当前激活页签后,其他 tab 同步更新激活状态。
  • 新打开的 tab 自动向已有 tab 请求最新 store 状态。

实现原理

同步插件基于 Pinia 插件机制实现:

  1. store 初始化时读取 sync 配置。
  2. 根据配置生成同步通道 channel。
  3. 通过 BroadcastChannel 建立同源 tab 通信。
  4. 不支持 BroadcastChannel 时,降级使用 localStorage 的 storage 事件。
  5. 当前 tab 的 store 发生变化时,通过 $subscribe 捕获变更并广播。
  6. 其他 tab 收到消息后,通过 store.$patch() 更新自己的 store。
  7. 通过 tabId 忽略自己发出的消息,避免重复 patch。
  8. 通过 storeId 保证只更新对应的 store。

简化流程:

Tab A 修改 store
        ↓
Pinia $subscribe 捕获变化
        ↓
提取需要同步的字段
        ↓
通过 BroadcastChannel/localStorage 广播
        ↓
Tab B / Tab C 收到消息
        ↓
校验 tabId、storeId
        ↓
store.$patch() 更新本地状态

注册插件

在应用创建 Pinia 实例后注册:

import { createPinia } from "pinia";
import { createPiniaSyncPlugin } from "@bams-app/store";

const pinia = createPinia();

pinia.use(createPiniaSyncPlugin());

app.use(pinia);

默认情况下,插件不会强制同步所有 store。只有满足以下条件之一的 store 会接入同步:

  • store 自身配置了 sync。
  • 插件配置了 stores 白名单,且当前 store 在白名单内。
  • 插件配置了 enabled: true,表示全量开启。

store 内配置 sync

推荐在需要同步的 store 内显式配置 sync。

import { defineStore } from "pinia";

export default defineStore("demo", {
  state: () => ({
    list: [],
    activeId: "",
    loading: false,
  }),
  sync: {
    pick: ["list", "activeId"],
  },
});

上面配置表示只同步 list 和 activeId,不会同步 loading。

tabs store 当前配置

当前 tabs store 已经接入同步:

sync: {
    channel: () => {
        const appStore = useAppStore();
        return `[bams-app]-pinia-sync-tabs-${appStore.appCode || "default"}`;
    },
    pick: ["openedTabs", "activeKey", "refreshingComponentNames", "refreshVersionMap"],
},

同步字段:

  • openedTabs:已打开页签列表。
  • activeKey:当前激活页签 key。
  • refreshingComponentNames:正在强制刷新的缓存组件名。
  • refreshVersionMap:每个 tab 的刷新版本号。

配置项说明

createPiniaSyncPlugin(options)

pinia.use(
  createPiniaSyncPlugin({
    channel: "bams-pinia-sync",
    stores: ["tabs", "menu"],
    enabled: false,
    manual: false,
    immediate: true,
    pick: ["fieldA"],
    omit: ["fieldB"],
    storeOptions: {
      tabs: {
        pick: ["openedTabs", "activeKey"],
      },
    },
  })
);

| 配置项 | 类型 | 默认值 | 说明 | | -------------- | ------------------------ | ----------------- | ------------------------------------------------------------- | | channel | string \| Function | bams-pinia-sync | 同步通道名。相同 channel 的同源页面才会互相同步。 | | stores | string \| string[] | - | store 白名单。配置后只有指定 store 会同步。 | | enabled | boolean | false | 是否在没有 store 级 sync 和 stores 白名单时全量开启同步。 | | manual | boolean | false | 是否手动模式。为 true 时不会自动监听 $subscribe 广播。 | | immediate | boolean | true | store 初始化后是否立即向其他 tab 请求最新状态。 | | pick | string[] | - | 只同步指定字段。优先级高于 omit。 | | paths | string[] | - | pick 的别名,兼容部分 persist 写法。 | | omit | string[] | - | 排除不需要同步的字段。 | | storeOptions | Record<string, object> | - | 按 storeId 单独覆盖同步配置。 |

store.sync

store 内的 sync 配置支持:

sync: true;

表示使用默认同步配置。

sync: false;

表示禁用当前 store 同步。

sync: {
    channel: "custom-channel",
    pick: ["list"],
    manual: true,
}

表示为当前 store 自定义同步配置。

store 内配置优先级高于插件全局配置。

动态 channel

channel 支持函数,用于按业务维度隔离同步范围。

sync: {
    channel: store => `bams-sync-${store.$id}`,
}

也可以结合其他 store 的状态:

sync: {
    channel: () => {
        const appStore = useAppStore();
        return `[bams-app]-pinia-sync-tabs-${appStore.appCode || "default"}`;
    },
}

动态 channel 会在 store 初始化时解析为最终字符串。

与 persist 的关系

persist 和 sync 是两套机制:

  • persist:负责刷新页面后从 localStorage 恢复数据。
  • sync:负责多个浏览器 tab 之间实时同步数据。

例如 tabs store 的持久化 key:

persist: {
    key: () => {
        const appStore = useAppStore();
        return `[bams-app]-tabs-${appStore.appCode || "default"}`;
    },
    storage: localStorage,
    pick: ["openedTabs", "activeKey"],
},

同步通道:

sync: {
    channel: () => {
        const appStore = useAppStore();
        return `[bams-app]-pinia-sync-tabs-${appStore.appCode || "default"}`;
    },
}

两者都使用 appCode 作为隔离维度:

persist key:  [bams-app]-tabs-${appCode}
sync channel: [bams-app]-pinia-sync-tabs-${appCode}

这样可以避免不同应用的数据互相影响。

手动刷新和广播

插件会在 store 实例上挂载 $sync:

const tabsStore = useTabsStore();

tabsStore.$sync.refresh(); // 向其他 tab 请求最新状态
tabsStore.$sync.broadcast(); // 主动广播当前状态
tabsStore.$sync.destroy(); // 销毁当前 store 的同步监听

也可以使用组合式 API:

import { usePiniaSync, useTabsStore } from "@bams-app/store";

const tabsStore = useTabsStore();
const { refresh, broadcast, destroy } = usePiniaSync(tabsStore);

refresh();
broadcast();
destroy();

也支持通过 storeId 获取已初始化的 store:

const { refresh } = usePiniaSync("tabs");

refresh();

手动模式

如果不希望每次 store 变化都自动广播,可以开启 manual:

export default defineStore("demo", {
  state: () => ({
    formData: {},
  }),
  sync: {
    pick: ["formData"],
    manual: true,
  },
});

开启后,需要手动广播:

const demoStore = useDemoStore();

demoStore.formData = { name: "test" };
demoStore.$sync.broadcast();

iframe 场景注意事项

跨 tab 同步能力受浏览器同源策略限制。

不同源 iframe

如果主应用和 iframe 不同源:

主应用: https://a.example.com
iframe: https://b.example.com

它们不会互相同步。

同源但 appCode 不同

如果多个 iframe 同源,但 appCode 不同:

iframe A: appCode=mes
iframe B: appCode=eam

当前 tabs store 使用 appCode 生成 channel,因此不会互相同步。

mes → [bams-app]-pinia-sync-tabs-mes
eam → [bams-app]-pinia-sync-tabs-eam

appCode 解析失败

如果路径或环境变量导致 appCode 为空,channel 会退化为:

[bams-app]-pinia-sync-tabs-default

多个应用都落到 default 时,会互相同步,造成数据串扰。

因此 iframe 场景中要确保每个应用都能正确解析到 appCode。

同源且 appCode 相同

如果多个 iframe 同源且 appCode 相同,它们会共享同一个 channel。

这适合“同一个应用多窗口同步”的场景。

如果业务要求即使 appCode 相同也要隔离不同 iframe 实例,需要在 channel 中增加实例维度,例如:

sync: {
    channel: () => {
        const appStore = useAppStore();
        const frameId = window.frameElement?.getAttribute("data-frame-id") || "main";
        return `[bams-app]-pinia-sync-tabs-${appStore.appCode || "default"}-${frameId}`;
    },
}

注意事项

  1. 只同步必要字段
    优先使用 pick,避免广播整个 store,减少数据量和误同步风险。

  2. 不要同步临时状态
    如 loading、error、定时器实例、DOM 引用等不建议同步。

  3. 确保 channel 有业务隔离维度
    多应用、多 iframe、多租户场景下,应在 channel 中加入 appCode、租户 ID 或实例 ID。

  4. 注意 appCode 为空的情况
    default channel 适合作为兜底,但不适合多个应用共存场景。

  5. 同源页面才会同步
    BroadcastChannel 和 localStorage storage 事件都受同源策略限制。

  6. 避免循环广播
    插件内部通过 applying 标记避免接收远端 patch 后再次广播。

  7. persist 不等于 sync
    persist.key 只影响本地持久化,不会自动隔离实时同步;实时同步必须通过 channel 隔离。

  8. 新 tab 初始化同步依赖已有 tab 响应
    immediate !== false 时,新 tab 会发送 request 请求状态。如果没有其他同 channel tab,则只使用自身当前状态或 persist 恢复的数据。

导出 API

export { createPiniaSyncPlugin, usePiniaSync, getPiniaSyncStore, broadcastPiniaStore, refreshPiniaStore } from "@bams-app/store";

| API | 说明 | | -------------------------------- | ---------------------------------------------------- | | createPiniaSyncPlugin(options) | 创建 Pinia 多 tab 同步插件。 | | usePiniaSync(storeOrId) | 组合式封装,提供 refresh、broadcast、destroy。 | | getPiniaSyncStore(storeId) | 根据 storeId 获取已初始化的 store 实例。 | | broadcastPiniaStore(store) | 手动广播某个 store 当前状态。 | | refreshPiniaStore(store) | 手动向其他 tab 请求某个 store 的最新状态。 |