|
| 1 | +# Computado e Observador |
| 2 | + |
| 3 | +> Esta secção usa a sintaxe de [Componentes Single File](../guide/single-file-component.html) para exemplos de código. |
| 4 | +
|
| 5 | +## `computado` |
| 6 | + |
| 7 | +Pega uma função getter e retorna um objecto [ref](./refs-api.html#ref) reativo imútavel para o valor retornado do getter. |
| 8 | + |
| 9 | +```js |
| 10 | +const count = ref(1) |
| 11 | +const plusOne = computed(() => count.value + 1) |
| 12 | + |
| 13 | +console.log(plusOne.value) // 2 |
| 14 | + |
| 15 | +plusOne.value++ // erro |
| 16 | +``` |
| 17 | + |
| 18 | +Como alternativa, ele pode usar um objeto com as funções `get` e `set` para criar um objecto ref gravável. |
| 19 | + |
| 20 | +```js |
| 21 | +const count = ref(1) |
| 22 | +const plusOne = computed({ |
| 23 | + get: () => count.value + 1, |
| 24 | + set: val => { |
| 25 | + count.value = val - 1 |
| 26 | + } |
| 27 | +}) |
| 28 | + |
| 29 | +plusOne.value = 1 |
| 30 | +console.log(count.value) // 0 |
| 31 | +``` |
| 32 | + |
| 33 | +**Digitando:** |
| 34 | + |
| 35 | +```ts |
| 36 | +// somente leitura |
| 37 | +function computed<T>(getter: () => T): Readonly<Ref<Readonly<T>>> |
| 38 | + |
| 39 | +// gravável |
| 40 | +function computed<T>(options: { get: () => T; set: (value: T) => void }): Ref<T> |
| 41 | +``` |
| 42 | + |
| 43 | +## `watchEffect` |
| 44 | + |
| 45 | +Executa uma função imediatamente enquanto rastreia reativamente suas dependências e a executa novamente sempre que as dependências são alteradas. |
| 46 | + |
| 47 | +```js |
| 48 | +const count = ref(0) |
| 49 | +
|
| 50 | +watchEffect(() => console.log(count.value)) |
| 51 | +// -> logs 0 |
| 52 | +
|
| 53 | +setTimeout(() => { |
| 54 | + count.value++ |
| 55 | + // -> logs 1 |
| 56 | +}, 100) |
| 57 | +``` |
| 58 | + |
| 59 | +**Digitando:** |
| 60 | + |
| 61 | +```ts |
| 62 | +function watchEffect( |
| 63 | + effect: (onInvalidate: InvalidateCbRegistrator) => void, |
| 64 | + options?: WatchEffectOptions |
| 65 | +): StopHandle |
| 66 | +
|
| 67 | +interface WatchEffectOptions { |
| 68 | + flush?: 'pre' | 'post' | 'sync' // default: 'pre' |
| 69 | + onTrack?: (event: DebuggerEvent) => void |
| 70 | + onTrigger?: (event: DebuggerEvent) => void |
| 71 | +} |
| 72 | +
|
| 73 | +interface DebuggerEvent { |
| 74 | + effect: ReactiveEffect |
| 75 | + target: any |
| 76 | + type: OperationTypes |
| 77 | + key: string | symbol | undefined |
| 78 | +} |
| 79 | +
|
| 80 | +type InvalidateCbRegistrator = (invalidate: () => void) => void |
| 81 | +
|
| 82 | +type StopHandle = () => void |
| 83 | +``` |
| 84 | + |
| 85 | +**Veja também**: [Guia `watchEffect`](../guide/reactivity-computed-watchers.html#watcheffect) |
| 86 | + |
| 87 | +## `watch` |
| 88 | + |
| 89 | +A API `watch` é o equivalente exato da API de opções [this.\$Watch](./instance-methods.html#watch) (e a opção [watch](./options-data.html#watch) correspondente ). `watch` requer a observação de uma fonte de dados específica e aplica efeitos colaterais em uma função de retorno de chamada separada. Também é preguiçoso por padrão - ou seja, o retorno de chamada só é chamado quando a fonte monitorada é alterada. |
| 90 | + |
| 91 | +- Comparado com [watchEffect](#watcheffect), `watch` nos permite: |
| 92 | + |
| 93 | + - Execute o efeito colateral preguiçosamente; |
| 94 | + - Seja mais específico sobre qual estado deve fazer com que o observador seja executado novamente; |
| 95 | + - Acesse o valor anterior e o atual do estado observado. |
| 96 | + |
| 97 | +### Observando uma única fonte |
| 98 | + |
| 99 | +Uma fonte de dados do inspetor pode ser uma função getter que retorna um valor ou diretamente um [ref](./refs-api.html#ref): |
| 100 | + |
| 101 | +```js |
| 102 | +// assistindo um getter |
| 103 | +const state = reactive({ count: 0 }) |
| 104 | +watch( |
| 105 | + () => state.count, |
| 106 | + (count, prevCount) => { |
| 107 | + /* ... */ |
| 108 | + } |
| 109 | +) |
| 110 | +
|
| 111 | +// assistindo diretamente um ref |
| 112 | +const count = ref(0) |
| 113 | +watch(count, (count, prevCount) => { |
| 114 | + /* ... */ |
| 115 | +}) |
| 116 | +``` |
| 117 | + |
| 118 | +### Observando a várias fontes |
| 119 | + |
| 120 | +Um observador também pode assistir a várias fontes ao mesmo tempo usando uma matriz: |
| 121 | + |
| 122 | +```js |
| 123 | +watch([fooRef, barRef], ([foo, bar], [prevFoo, prevBar]) => { |
| 124 | + /* ... */ |
| 125 | +}) |
| 126 | +``` |
| 127 | + |
| 128 | +### Comportamento compartilhado com `watchEffect` |
| 129 | + |
| 130 | +`watch` compartilha o comportamento [`watchEffect`](#watcheffect) em termos de [interrupção manual](../guide/reactivity-computed-watchers.html#stopping-the-watcher), [invalidação de efeito colateral](../guide/reactivity-computed-watchers.html#side-effect-invalidation) (com `onInvalidate` passado para o retorno de chamada como o terceiro argument), [tempo de libertação](../guide/reactivity-computed-watchers.html#effect-flush-timing) and [depuração](../guide/reactivity-computed-watchers.html#watcher-debugging). |
| 131 | + |
| 132 | +**Digitando:** |
| 133 | + |
| 134 | +```ts |
| 135 | +// observando uma única fonte |
| 136 | +function watch<T>( |
| 137 | + source: WatcherSource<T>, |
| 138 | + callback: ( |
| 139 | + value: T, |
| 140 | + oldValue: T, |
| 141 | + onInvalidate: InvalidateCbRegistrator |
| 142 | + ) => void, |
| 143 | + options?: WatchOptions |
| 144 | +): StopHandle |
| 145 | +
|
| 146 | +// Observando a várias fontes |
| 147 | +function watch<T extends WatcherSource<unknown>[]>( |
| 148 | + sources: T |
| 149 | + callback: ( |
| 150 | + values: MapSources<T>, |
| 151 | + oldValues: MapSources<T>, |
| 152 | + onInvalidate: InvalidateCbRegistrator |
| 153 | + ) => void, |
| 154 | + options? : WatchOptions |
| 155 | +): StopHandle |
| 156 | +
|
| 157 | +type WatcherSource<T> = Ref<T> | (() => T) |
| 158 | +
|
| 159 | +type MapSources<T> = { |
| 160 | + [K in keyof T]: T[K] extends WatcherSource<infer V> ? V : never |
| 161 | +} |
| 162 | +
|
| 163 | +// veja a digitação `watchEffect` para opções compartilhadas |
| 164 | +interface WatchOptions extends WatchEffectOptions { |
| 165 | + immediate?: boolean // padrão: false |
| 166 | + deep?: boolean |
| 167 | +} |
| 168 | +``` |
| 169 | + |
| 170 | +**Veja também**: [Guia `watch`](../guide/reactivity-computed-watchers.html#watch) |
0 commit comments