Svelte
@iostore/svelte 提供标准 Svelte Store 适配器,便于与 $store 语法协作。
- 在 Svelte 组件中直接订阅 IO。
- 使用
$语法简化模板读取。 - 需要可控读写边界(只读 / 可写)。
安装相关依赖(任选一种包管理工具):
npm i @iostore/store @iostore/sveltepnpm add @iostore/store @iostore/svelteyarn add @iostore/store @iostore/sveltebun add @iostore/store @iostore/sveltetoReadable(只读)
Section titled “toReadable(只读)”import { io } from '@iostore/store';import { toReadable } from '@iostore/svelte';
const store = io({ count: 0 });const readable = toReadable(store.count);toWritable(可写)
Section titled “toWritable(可写)”import { toWritable } from '@iostore/svelte';
const writable = toWritable(store.count);const readable = toReadable(store.count, { schedule: 'sync' });可选值:sync | microtask | animationFrame。
API 速查
Section titled “API 速查”| 场景 | API | 说明 |
|---|---|---|
| 只读适配 | toReadable(unitOrDerived, options?) | 生成只读 Svelte store。 |
| 可写适配 | toWritable(unit, options?) | 生成可写 Svelte store。 |
| 通知调度 | options.schedule | sync / microtask / animationFrame。 |
| 核心写入 | `unit.set(next | updater)` |
| 批量写入 | batch(fn) | 合并更新,减少 UI 抖动。 |
错误示例与推荐写法
Section titled “错误示例与推荐写法”// 错误:仅展示也使用 toWritableconst count = toWritable(store.count);
// 推荐:展示优先 toReadableconst countView = toReadable(store.count);// 错误:高频更新不控频const input = toWritable(store.keyword);
// 推荐:在写入链路上配合 throttle/debounce// 详见 /cookbook/throttle 与 /cookbook/debounce- 只需要展示时使用
toWritable,导致写入边界不清晰。 - 组件外直接持有大量可写 store,增加状态耦合。
- 高频变更未配合节流/防抖。