API
响应式 API
本文档介绍 TSone 响应式系统的 API。
核心函数总览
| 名称 | 签名 | 说明 |
|---|---|---|
reactive | reactive<T extends object>(target: T): T | 创建响应式代理对象。 |
effect | effect(fn: () => void, options?): EffectRunner | 创建副作用函数,在依赖变化时重新执行。 |
computed | computed<T>(getter: () => T): { value: T } | 创建带缓存的计算属性。 |
ref | ref<T>(value: T): { value: T } | 创建单值响应式引用。 |
isRef | isRef(value: unknown): boolean | 检查值是否为 ref 引用。 |
unref | unref<T>(value: T | Ref<T>): T | 如果传入 ref 则返回 value,否则返回原值。 |
readonly | readonly<T extends object>(target: T): T | 创建只读响应式代理对象。 |
stop | stop(effect: EffectRunner): void | 停止一个副作用函数继续响应更新。 |
nextTick | nextTick(): Promise<void> | 等待当前批次的响应式 effect(组件重渲染)执行完成。修改 state 后需要读取最新 DOM 时使用。 |
flushSync | flushSync(): void | 同步冲刷待执行的响应式 effect,立即完成组件重渲染。一般仅测试或需要同步读 DOM 的场景使用。 |
watch | watch(source, callback, options?): () => void | 侦听响应式源(getter 或 ref)的变化并执行回调,支持 immediate(建立后立即回调)、deep(深度追踪嵌套属性)与 sync(同步回调)选项;返回停止侦听的函数。 |
isReactive | isReactive(value: unknown): boolean | 检查对象是否为响应式代理。 |
isReadonly | isReadonly(value: unknown): boolean | 检查对象是否为只读响应式代理。 |
reactive
import { reactive } from '@geektech/tsone';
const state = reactive({
count: 0,
user: { name: 'John', age: 30 },
});effect
import { effect, reactive } from '@geektech/tsone';
const state = reactive({ count: 0 });
effect(() => {
console.log(`Count: ${state.count}`);
});
state.count = 1;computed
import { computed, reactive } from '@geektech/tsone';
const state = reactive({ count: 0 });
const doubleCount = computed(() => state.count * 2);
console.log(doubleCount.value);readonly
import { reactive, readonly } from '@geektech/tsone';
const original = reactive({ count: 0 });
const readOnlyState = readonly(original);stop
import { effect, reactive, stop } from '@geektech/tsone';
const state = reactive({ count: 0 });
const runner = effect(() => {
console.log(`Count: ${state.count}`);
});
stop(runner);ref
import { effect, ref } from '@geektech/tsone';
const count = ref(0);
effect(() => {
console.log(count.value);
});示例
import { computed, effect, reactive, readonly, ref, stop } from '@geektech/tsone';
const state = reactive({ count: 0 });
const countRef = ref(1);
const doubleCount = computed(() => state.count * 2 + countRef.value);
const runner = effect(() => {
console.log(state.count, doubleCount.value);
});
const frozen = readonly(state);
console.log(frozen.count);
stop(runner);