0
# Vue Reactivity
1
2
Vue Reactivity is a standalone reactive state management system that enables fine-grained reactive programming through proxies and dependency tracking. It provides reactive references, reactive objects, computed values, effects, and watchers that automatically track dependencies and trigger updates when state changes.
3
4
## Package Information
5
6
- **Package Name**: @vue/reactivity
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @vue/reactivity`
10
11
## Core Imports
12
13
```typescript
14
import {
15
ref, reactive, computed, effect, watch,
16
isRef, isReactive, toRaw, unref
17
} from "@vue/reactivity";
18
```
19
20
For CommonJS:
21
22
```javascript
23
const {
24
ref, reactive, computed, effect, watch,
25
isRef, isReactive, toRaw, unref
26
} = require("@vue/reactivity");
27
```
28
29
## Basic Usage
30
31
```typescript
32
import { ref, reactive, computed, effect, watch } from "@vue/reactivity";
33
34
// Create reactive references
35
const count = ref(0);
36
const name = ref("Vue");
37
38
// Create reactive objects
39
const state = reactive({
40
items: [],
41
loading: false
42
});
43
44
// Create computed values
45
const doubleCount = computed(() => count.value * 2);
46
47
// Run side effects
48
effect(() => {
49
console.log(`Count is: ${count.value}`);
50
});
51
52
// Watch for changes
53
watch(count, (newValue, oldValue) => {
54
console.log(`Count changed from ${oldValue} to ${newValue}`);
55
});
56
57
// Modify reactive data
58
count.value = 5; // Triggers effect and watcher
59
state.loading = true; // Reactive update
60
```
61
62
## Architecture
63
64
Vue Reactivity is built around several key components:
65
66
- **Reactive References**: Wrappers around primitive values that track access and mutations (`ref`, `shallowRef`)
67
- **Reactive Objects**: Proxy-based reactive objects that track property access and changes (`reactive`, `readonly`)
68
- **Dependency Tracking**: Automatic dependency collection and effect triggering system (`track`, `trigger`)
69
- **Computed Values**: Cached derived values that update when dependencies change (`computed`)
70
- **Effects System**: Side effect functions that re-run when dependencies change (`effect`, `ReactiveEffect`)
71
- **Watchers**: Observation system for reactive data changes with callbacks (`watch`)
72
- **Effect Scopes**: Grouping and cleanup management for effects (`effectScope`)
73
74
## Capabilities
75
76
### Reactive References
77
78
Core reactive reference system for wrapping primitive values and providing fine-grained reactivity tracking.
79
80
```typescript { .api }
81
function ref<T>(value: T): Ref<UnwrapRef<T>, UnwrapRef<T> | T>;
82
function shallowRef<T>(value: T): ShallowRef<T>;
83
function isRef<T>(r: Ref<T> | unknown): r is Ref<T>;
84
function unref<T>(ref: MaybeRef<T> | ComputedRef<T>): T;
85
function triggerRef(ref: Ref): void;
86
87
interface Ref<T = any, S = T> {
88
get value(): T;
89
set value(_: S);
90
}
91
```
92
93
[Reactive References](./refs.md)
94
95
### Reactive Objects
96
97
Proxy-based reactive objects that provide deep reactivity tracking for complex data structures.
98
99
```typescript { .api }
100
function reactive<T extends object>(target: T): Reactive<T>;
101
function readonly<T extends object>(target: T): DeepReadonly<UnwrapNestedRefs<T>>;
102
function shallowReactive<T extends object>(target: T): ShallowReactive<T>;
103
function shallowReadonly<T extends object>(target: T): Readonly<T>;
104
function isReactive(value: unknown): boolean;
105
function isReadonly(value: unknown): boolean;
106
function toRaw<T>(observed: T): T;
107
```
108
109
[Reactive Objects](./reactive-objects.md)
110
111
### Computed Values
112
113
Cached derived values that automatically update when their dependencies change, with support for both readonly and writable computed properties.
114
115
```typescript { .api }
116
function computed<T>(getter: ComputedGetter<T>): ComputedRef<T>;
117
function computed<T, S = T>(options: WritableComputedOptions<T, S>): WritableComputedRef<T, S>;
118
119
interface ComputedRef<T = any> {
120
readonly value: T;
121
}
122
123
type ComputedGetter<T> = (oldValue?: T) => T;
124
```
125
126
[Computed Values](./computed.md)
127
128
### Effects System
129
130
Reactive effect system that automatically tracks dependencies and re-runs functions when reactive data changes.
131
132
```typescript { .api }
133
function effect<T = any>(fn: () => T, options?: ReactiveEffectOptions): ReactiveEffectRunner<T>;
134
function stop(runner: ReactiveEffectRunner): void;
135
function onEffectCleanup(fn: () => void): void;
136
137
class ReactiveEffect<T = any> {
138
constructor(public fn: () => T);
139
run(): T;
140
stop(): void;
141
trigger(): void;
142
}
143
```
144
145
[Effects System](./effects.md)
146
147
### Watchers
148
149
Advanced observation system for reactive data changes with customizable callbacks, immediate execution, and deep watching options.
150
151
```typescript { .api }
152
function watch<T>(
153
source: WatchSource<T> | WatchSource<T>[],
154
cb: WatchCallback<T>,
155
options?: WatchOptions
156
): WatchHandle;
157
158
interface WatchHandle {
159
pause: () => void;
160
resume: () => void;
161
stop: () => void;
162
}
163
164
type WatchCallback<V = any, OV = any> = (
165
value: V,
166
oldValue: OV,
167
onCleanup: (fn: () => void) => void
168
) => any;
169
```
170
171
[Watchers](./watchers.md)
172
173
### Effect Scopes
174
175
Grouping and cleanup management system for organizing and disposing of effects in a controlled manner.
176
177
```typescript { .api }
178
function effectScope(detached?: boolean): EffectScope;
179
function getCurrentScope(): EffectScope | undefined;
180
function onScopeDispose(fn: () => void): void;
181
182
class EffectScope {
183
get active(): boolean;
184
run<T>(fn: () => T): T | undefined;
185
stop(): void;
186
pause(): void;
187
resume(): void;
188
}
189
```
190
191
[Effect Scopes](./effect-scopes.md)
192
193
### Low-level Dependency Tracking
194
195
Low-level functions for manual dependency tracking and triggering. These are typically used internally but are available for advanced use cases.
196
197
```typescript { .api }
198
function track(target: object, type: TrackOpTypes, key: unknown): void;
199
function trigger(
200
target: object,
201
type: TriggerOpTypes,
202
key?: unknown,
203
newValue?: unknown,
204
oldValue?: unknown,
205
oldTarget?: Map<unknown, unknown> | Set<unknown>
206
): void;
207
208
// Iteration tracking keys
209
const ITERATE_KEY: unique symbol;
210
const ARRAY_ITERATE_KEY: unique symbol;
211
const MAP_KEY_ITERATE_KEY: unique symbol;
212
```
213
214
### Array Instrumentations
215
216
Functions for handling reactive array reading with proper dependency tracking.
217
218
```typescript { .api }
219
function reactiveReadArray<T>(array: T[]): T[];
220
function shallowReadArray<T>(arr: T[]): T[];
221
```
222
223
### Tracking Control
224
225
Functions for manually controlling dependency tracking state during effect execution.
226
227
```typescript { .api }
228
function enableTracking(): void;
229
function pauseTracking(): void;
230
function resetTracking(): void;
231
```
232
233
### Utility Functions
234
235
Utility functions for converting between reactive and non-reactive values, type checking, and advanced reactive operations.
236
237
```typescript { .api }
238
function toRef<T>(value: T): ToRef<T>;
239
function toRefs<T extends object>(object: T): ToRefs<T>;
240
function toValue<T>(source: MaybeRefOrGetter<T>): T;
241
function markRaw<T extends object>(value: T): Raw<T>;
242
function customRef<T>(factory: CustomRefFactory<T>): Ref<T>;
243
function proxyRefs<T extends object>(objectWithRefs: T): ShallowUnwrapRef<T>;
244
function isProxy(value: any): boolean;
245
function isShallow(value: unknown): boolean;
246
function toReactive<T>(value: T): T;
247
function toReadonly<T>(value: T): T;
248
```
249
250
[Utility Functions](./utilities.md)
251
252
## Types
253
254
```typescript { .api }
255
// Core reference types
256
type MaybeRef<T = any> = T | Ref<T> | ShallowRef<T> | WritableComputedRef<T>;
257
type MaybeRefOrGetter<T = any> = MaybeRef<T> | ComputedRef<T> | (() => T);
258
type UnwrapRef<T> = T extends ShallowRef<infer V> ? V : T extends Ref<infer V> ? UnwrapRefSimple<V> : UnwrapRefSimple<T>;
259
type ShallowUnwrapRef<T> = { [K in keyof T]: DistributeRef<T[K]> };
260
type UnwrapNestedRefs<T> = T extends Ref ? T : UnwrapRefSimple<T>;
261
262
// Reactive object types
263
type Reactive<T> = UnwrapNestedRefs<T>;
264
type DeepReadonly<T> = { readonly [P in keyof T]: DeepReadonly<T[P]> };
265
type ShallowReactive<T> = T;
266
type Raw<T> = T & { [RawSymbol]?: true };
267
268
// Utility types
269
type ToRef<T> = [T] extends [Ref] ? T : Ref<T>;
270
type ToRefs<T = any> = { [K in keyof T]: ToRef<T[K]> };
271
272
// Effect and watch types
273
type ReactiveEffectRunner<T = any> = (() => T) & { effect: ReactiveEffect };
274
type WatchSource<T = any> = Ref<T, any> | ComputedRef<T> | (() => T);
275
type CustomRefFactory<T> = (track: () => void, trigger: () => void) => { get: () => T; set: (value: T) => void };
276
277
// Options types
278
interface ReactiveEffectOptions {
279
scheduler?: EffectScheduler;
280
allowRecurse?: boolean;
281
onStop?: () => void;
282
}
283
284
interface WritableComputedOptions<T, S = T> {
285
get: ComputedGetter<T>;
286
set: ComputedSetter<S>;
287
}
288
```
289
290
## Constants and Enums
291
292
```typescript { .api }
293
enum TrackOpTypes {
294
GET = 'get',
295
HAS = 'has',
296
ITERATE = 'iterate'
297
}
298
299
enum TriggerOpTypes {
300
SET = 'set',
301
ADD = 'add',
302
DELETE = 'delete',
303
CLEAR = 'clear'
304
}
305
306
enum ReactiveFlags {
307
SKIP = '__v_skip',
308
IS_REACTIVE = '__v_isReactive',
309
IS_READONLY = '__v_isReadonly',
310
IS_SHALLOW = '__v_isShallow',
311
RAW = '__v_raw',
312
IS_REF = '__v_isRef'
313
}
314
315
enum EffectFlags {
316
ACTIVE = 1,
317
RUNNING = 2,
318
TRACKING = 4,
319
NOTIFIED = 8,
320
DIRTY = 16,
321
ALLOW_RECURSE = 32,
322
PAUSED = 64,
323
EVALUATED = 128
324
}
325
```