跳转到内容

Svelte

@iostore/svelte 提供标准 Svelte Store 适配器,便于与 $store 语法协作。

  • 在 Svelte 组件中直接订阅 IO。
  • 使用 $ 语法简化模板读取。
  • 需要可控读写边界(只读 / 可写)。

安装相关依赖(任选一种包管理工具):

Terminal window
npm i @iostore/store @iostore/svelte
import { io } from '@iostore/store';
import { toReadable } from '@iostore/svelte';
const store = io({ count: 0 });
const readable = toReadable(store.count);
import { toWritable } from '@iostore/svelte';
const writable = toWritable(store.count);
const readable = toReadable(store.count, { schedule: 'sync' });

可选值:sync | microtask | animationFrame

场景API说明
只读适配toReadable(unitOrDerived, options?)生成只读 Svelte store。
可写适配toWritable(unit, options?)生成可写 Svelte store。
通知调度options.schedulesync / microtask / animationFrame
核心写入`unit.set(nextupdater)`
批量写入batch(fn)合并更新,减少 UI 抖动。
// 错误:仅展示也使用 toWritable
const count = toWritable(store.count);
// 推荐:展示优先 toReadable
const countView = toReadable(store.count);
// 错误:高频更新不控频
const input = toWritable(store.keyword);
// 推荐:在写入链路上配合 throttle/debounce
// 详见 /cookbook/throttle 与 /cookbook/debounce
  • 只需要展示时使用 toWritable,导致写入边界不清晰。
  • 组件外直接持有大量可写 store,增加状态耦合。
  • 高频变更未配合节流/防抖。
  • 默认展示用 toReadable,交互输入再切 toWritable
  • 保持“单向数据流 + 局部可写”策略。
  • 高频交互结合 Throttle / Debounce
  • 学习 订阅 的值与更新区别。
  • 需要 SSR 时,查看 SvelteKit 实战章节。