Skip to content

Commit 98b1560

Browse files
committed
docs: move reactivity transform docs
1 parent 8384c16 commit 98b1560

File tree

2 files changed

+548
-4
lines changed

2 files changed

+548
-4
lines changed

docs/features/reactivity-transform.md

Lines changed: 274 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,278 @@ module.exports = {
8282
}
8383
```
8484

85-
## Usage
85+
## Refs vs. Reactive Variables {#refs-vs-reactive-variables}
8686

87-
Refer to [official docs](https://vuejs.org/guide/extras/reactivity-transform.html).
87+
Ever since the introduction of the Composition API, one of the primary unresolved questions is the use of refs vs. reactive objects. It's easy to lose reactivity when destructuring reactive objects, while it can be cumbersome to use `.value` everywhere when using refs. Also, `.value` is easy to miss if not using a type system.
88+
89+
Reactivity Transform is a compile-time transform that allows us to write code like this:
90+
91+
```vue
92+
<script setup>
93+
let count = $ref(0)
94+
95+
console.log(count)
96+
97+
function increment() {
98+
count++
99+
}
100+
</script>
101+
102+
<template>
103+
<button @click="increment">{{ count }}</button>
104+
</template>
105+
```
106+
107+
The `$ref()` method here is a **compile-time macro**: it is not an actual method that will be called at runtime. Instead, the Vue compiler uses it as a hint to treat the resulting `count` variable as a **reactive variable.**
108+
109+
Reactive variables can be accessed and re-assigned just like normal variables, but these operations are compiled into refs with `.value`. For example, the `<script>` part of the above component is compiled into:
110+
111+
```js{5,8}
112+
import { ref } from 'vue'
113+
114+
let count = ref(0)
115+
116+
console.log(count.value)
117+
118+
function increment() {
119+
count.value++
120+
}
121+
```
122+
123+
Every reactivity API that returns refs will have a `$`-prefixed macro equivalent. These APIs include:
124+
125+
- [`ref`](https://vuejs.org/api/reactivity-core#ref) -> `$ref`
126+
- [`computed`](https://vuejs.org/api/reactivity-core#computed) -> `$computed`
127+
- [`shallowRef`](https://vuejs.org/api/reactivity-advanced#shallowref) -> `$shallowRef`
128+
- [`customRef`](https://vuejs.org/api/reactivity-advanced#customref) -> `$customRef`
129+
- [`toRef`](https://vuejs.org/api/reactivity-utilities#toref) -> `$toRef`
130+
131+
These macros are globally available and do not need to be imported when Reactivity Transform is enabled, but you can optionally import them from `vue/macros` if you want to be more explicit:
132+
133+
```js
134+
import { $ref } from 'vue/macros'
135+
136+
const count = $ref(0)
137+
```
138+
139+
## Destructuring with `$()` {#destructuring-with}
140+
141+
It is common for a composition function to return an object of refs, and use destructuring to retrieve these refs. For this purpose, reactivity transform provides the **`$()`** macro:
142+
143+
```js
144+
import { useMouse } from '@vueuse/core'
145+
146+
const { x, y } = $(useMouse())
147+
148+
console.log(x, y)
149+
```
150+
151+
Compiled output:
152+
153+
```js
154+
import { toRef } from 'vue'
155+
import { useMouse } from '@vueuse/core'
156+
157+
const __temp = useMouse(),
158+
x = toRef(__temp, 'x'),
159+
y = toRef(__temp, 'y')
160+
161+
console.log(x.value, y.value)
162+
```
163+
164+
Note that if `x` is already a ref, `toRef(__temp, 'x')` will simply return it as-is and no additional ref will be created. If a destructured value is not a ref (e.g. a function), it will still work - the value will be wrapped in a ref so the rest of the code works as expected.
165+
166+
`$()` destructure works on both reactive objects **and** plain objects containing refs.
167+
168+
## Convert Existing Refs to Reactive Variables with `$()` {#convert-existing-refs-to-reactive-variables-with}
169+
170+
In some cases we may have wrapped functions that also return refs. However, the Vue compiler won't be able to know ahead of time that a function is going to return a ref. In such cases, the `$()` macro can also be used to convert any existing refs into reactive variables:
171+
172+
```js
173+
function myCreateRef() {
174+
return ref(0)
175+
}
176+
177+
const count = $(myCreateRef())
178+
```
179+
180+
## Reactive Props Destructure {#reactive-props-destructure}
181+
182+
There are two pain points with the current `defineProps()` usage in `<script setup>`:
183+
184+
1. Similar to `.value`, you need to always access props as `props.x` in order to retain reactivity. This means you cannot destructure `defineProps` because the resulting destructured variables are not reactive and will not update.
185+
186+
2. When using the [type-only props declaration](https://vuejs.org/api/sfc-script-setup.html#typescript-only-features), there is no easy way to declare default values for the props. We introduced the `withDefaults()` API for this exact purpose, but it's still clunky to use.
187+
188+
We can address these issues by applying a compile-time transform when `defineProps` is used with destructuring, similar to what we saw earlier with `$()`:
189+
190+
```html
191+
<script setup lang="ts">
192+
interface Props {
193+
msg: string
194+
count?: number
195+
foo?: string
196+
}
197+
198+
const {
199+
msg,
200+
// default value just works
201+
count = 1,
202+
// local aliasing also just works
203+
// here we are aliasing `props.foo` to `bar`
204+
foo: bar,
205+
} = defineProps<Props>()
206+
207+
watchEffect(() => {
208+
// will log whenever the props change
209+
console.log(msg, count, bar)
210+
})
211+
</script>
212+
```
213+
214+
The above will be compiled into the following runtime declaration equivalent:
215+
216+
```js
217+
export default {
218+
props: {
219+
msg: { type: String, required: true },
220+
count: { type: Number, default: 1 },
221+
foo: String,
222+
},
223+
setup(props) {
224+
watchEffect(() => {
225+
console.log(props.msg, props.count, props.foo)
226+
})
227+
},
228+
}
229+
```
230+
231+
## Retaining Reactivity Across Function Boundaries {#retaining-reactivity-across-function-boundaries}
232+
233+
While reactive variables relieve us from having to use `.value` everywhere, it creates an issue of "reactivity loss" when we pass reactive variables across function boundaries. This can happen in two cases:
234+
235+
### Passing into function as argument {#passing-into-function-as-argument}
236+
237+
Given a function that expects a ref as an argument, e.g.:
238+
239+
```ts
240+
function trackChange(x: Ref<number>) {
241+
watch(x, (x) => {
242+
console.log('x changed!')
243+
})
244+
}
245+
246+
const count = $ref(0)
247+
trackChange(count) // doesn't work!
248+
```
249+
250+
The above case will not work as expected because it compiles to:
251+
252+
```ts
253+
const count = ref(0)
254+
trackChange(count.value)
255+
```
256+
257+
Here `count.value` is passed as a number, whereas `trackChange` expects an actual ref. This can be fixed by wrapping `count` with `$$()` before passing it:
258+
259+
```diff
260+
let count = $ref(0)
261+
- trackChange(count)
262+
+ trackChange($$(count))
263+
```
264+
265+
The above compiles to:
266+
267+
```js
268+
import { ref } from 'vue'
269+
270+
const count = ref(0)
271+
trackChange(count)
272+
```
273+
274+
As we can see, `$$()` is a macro that serves as an **escape hint**: reactive variables inside `$$()` will not get `.value` appended.
275+
276+
### Returning inside function scope {#returning-inside-function-scope}
277+
278+
Reactivity can also be lost if reactive variables are used directly in a returned expression:
279+
280+
```ts
281+
function useMouse() {
282+
const x = $ref(0)
283+
const y = $ref(0)
284+
285+
// listen to mousemove...
286+
287+
// doesn't work!
288+
return {
289+
x,
290+
y,
291+
}
292+
}
293+
```
294+
295+
The above return statement compiles to:
296+
297+
```ts
298+
return {
299+
x: x.value,
300+
y: y.value,
301+
}
302+
```
303+
304+
In order to retain reactivity, we should be returning the actual refs, not the current value at return time.
305+
306+
Again, we can use `$$()` to fix this. In this case, `$$()` can be used directly on the returned object - any reference to reactive variables inside the `$$()` call will retain the reference to their underlying refs:
307+
308+
```ts
309+
function useMouse() {
310+
const x = $ref(0)
311+
const y = $ref(0)
312+
313+
// listen to mousemove...
314+
315+
// fixed
316+
return $$({
317+
x,
318+
y,
319+
})
320+
}
321+
```
322+
323+
### Using `$$()` on destructured props {#using-on-destructured-props}
324+
325+
`$$()` works on destructured props since they are reactive variables as well. The compiler will convert it with `toRef` for efficiency:
326+
327+
```ts
328+
const { count } = defineProps<{ count: number }>()
329+
330+
passAsRef($$(count))
331+
```
332+
333+
compiles to:
334+
335+
```js
336+
export default {
337+
setup(props) {
338+
const __props_count = toRef(props, 'count')
339+
passAsRef(__props_count)
340+
},
341+
}
342+
```
343+
344+
## TypeScript Integration <sup class="vt-badge ts" /> {#typescript-integration}
345+
346+
Vue provides typings for these macros (available globally) and all types will work as expected. There are no incompatibilities with standard TypeScript semantics, so the syntax will work with all existing tooling.
347+
348+
This also means the macros can work in any files where valid JS / TS are allowed - not just inside Vue SFCs.
349+
350+
Since the macros are available globally, their types need to be explicitly referenced (e.g. in a `env.d.ts` file):
351+
352+
```ts
353+
/// <reference types="unplugin-vue-macros/macros-global" />
354+
355+
// or for standalone version:
356+
/// <reference types="@vue-macros/reactivity-transform/macros-global" />
357+
```
358+
359+
When explicitly importing the macros from `vue/macros`, the type will work without declaring the globals.

0 commit comments

Comments
 (0)