@idooel/runtime-context
Version:
Runtime data pool with namespaces, stackable contexts, subscriptions and optional persistence. Vue adapter included.
93 lines (71 loc) • 2.47 kB
Markdown
轻量运行时数据池与上下文管理(TS),支持:
- 命名空间 + KV 存取(自动添加 `idooel` 前缀避免冲突)
- 可嵌套的上下文栈(覆盖读取)
- 订阅变更(按 ns/key 过滤)
- Vue 2.7+ 适配(插件 + `useDataPool` + `usePoolValue`)(可选)
```bash
pnpm add @idooel/runtime-context
```
```ts
import { createDataPool } from '@idooel/runtime-context/core'
const pool = createDataPool()
// 命名空间操作(自动添加 idooel 前缀)
pool.set('user', 'token', 'abc') // 实际存储为 'idooel.user'
pool.get('user', 'token') // 'abc'
// 上下文隔离
const ctx = pool.createContext({ user: { tenant: 't1' } })
pool.runInContext(ctx, () => {
pool.set('user', 'token', 'ctx-token') // 当前上下文
pool.get('user', 'token') // 'ctx-token'
})
// 订阅变更
const off = pool.subscribe({ ns: 'user', key: 'token' }, (e) => {
console.log('token changed:', e.value, 'actual ns:', e.ns) // 'idooel.user'
})
pool.set('user', 'token', 'xyz') // 触发订阅
off()
```
```ts
import Vue from 'vue'
import { Vue2DataPoolPlugin } from '@idooel/runtime-context/vue2'
Vue.use(Vue2DataPoolPlugin)
// 在组件中使用
export default {
created() {
this.$idooelDataPool.set('user', 'token', 'abc')
const token = this.$idooelDataPool.get('user', 'token')
}
}
```
```ts
// 完整功能(核心 + Vue)
import { createDataPool, Vue2DataPoolPlugin } from '@idooel/runtime-context'
// 仅核心功能
import { createDataPool } from '@idooel/runtime-context/core'
// 仅 Vue 2 集成
import { Vue2DataPoolPlugin } from '@idooel/runtime-context/vue2'
```
- 所有命名空间自动添加 `idooel` 前缀(内部存储)
- 避免与其他库或应用的全局数据冲突
- **保持 API 一致性**:用户使用的命名空间始终不带前缀
- 订阅事件中的命名空间也保持用户友好的格式
- 核心库独立于框架
- Vue 2 集成作为可选模块
- 支持按需导入减少包体积
- 完整的 TypeScript 支持
- 泛型类型推导
- 编译时类型检查
更多用法见源码导出的类型与注释和 `/examples` 目录。
注意:
- 当前版本未启用本地持久化。
- 命名空间会自动添加 `idooel` 前缀(如 `user` → `idooel.user`)。