Skip to content

Commit 34168d2

Browse files
committed
Translation of guide/reactivity-computed-watchers
1 parent d4f1897 commit 34168d2

File tree

1 file changed

+73
-73
lines changed

1 file changed

+73
-73
lines changed

src/guide/reactivity-computed-watchers.md

Lines changed: 73 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,21 @@
1-
# Computed and Watch
1+
# Dados Computados e Observadores
22

3-
> This section uses [single-file component](single-file-component.html) syntax for code examples
3+
> Esta seção usa a sintaxe de [componente de single-file](single-file-component.html) para exemplos de código
44
5-
## Computed values
5+
## Valores computados
66

7-
Sometimes we need state that depends on other state - in Vue this is handled with component [computed properties](computed.html#computed-properties). To directly create a computed value, we can use the `computed` function: it takes a getter function and returns an immutable reactive [ref](reactivity-fundamentals.html#creating-standalone-reactive-values-as-refs) object for the returned value from the getter.
7+
Às vezes precisamos de um estado que depende de outro estado - no Vue isso é tratado com [dados computados](computed.html#computed-properties) do componente. Para criar diretamente um valor computado, podemos usar a função `computed`: ela pega uma função _getter_ e retorna um objeto reativo imutável [ref](reactivity-fundamentals.html#criacao-de-valores-reativos-avulsos-como-refs) para o valor retornado do _getter_.
88

99
```js
1010
const count = ref(1)
1111
const plusOne = computed(() => count.value + 1)
1212

1313
console.log(plusOne.value) // 2
1414

15-
plusOne.value++ // error
15+
plusOne.value++ // erro
1616
```
1717

18-
Alternatively, it can take an object with `get` and `set` functions to create a writable ref object.
18+
Alternativamente, ele pode receber um objeto com as funções `get` e `set` para criar um objeto _ref_ modificável.
1919

2020
```js
2121
const count = ref(1)
@@ -30,102 +30,102 @@ plusOne.value = 1
3030
console.log(count.value) // 0
3131
```
3232

33-
### Computed Debugging <Badge text="3.2+" />
33+
### Depuração de Computados <Badge text="3.2+" />
3434

35-
`computed` accepts a second argument with `onTrack` and `onTrigger` options:
35+
`computed` aceita um segundo argumento com as opções `onTrack` e `onTrigger`:
3636

37-
- `onTrack` will be called when a reactive property or ref is tracked as a dependency.
38-
- `onTrigger` will be called when the watcher callback is triggered by the mutation of a dependency.
37+
- `onTrack` será chamado quando uma propriedade reativa ou _ref_ for rastreada como uma dependência.
38+
- `onTrigger` será chamado quando o _callback_ do observador for acionado pela mutação de uma dependência.
3939

40-
Both callbacks will receive a debugger event which contains information on the dependency in question. It is recommended to place a `debugger` statement in these callbacks to interactively inspect the dependency:
40+
Ambos os _callbacks_ receberão um evento depurador que contém informações sobre a dependência em questão. Recomenda-se colocar uma instrução `debugger` nesses _callbacks_ para inspecionar interativamente a dependência:
4141

4242
```js
4343
const plusOne = computed(() => count.value + 1, {
4444
onTrack(e) {
45-
// triggered when count.value is tracked as a dependency
45+
// acionado quando count.value é rastreado como uma dependência
4646
debugger
4747
},
4848
onTrigger(e) {
49-
// triggered when count.value is mutated
49+
// acionado quando count.value é modificado
5050
debugger
5151
}
5252
})
5353

54-
// access plusOne, should trigger onTrack
54+
// acessa plusOne, deve acionar onTrack
5555
console.log(plusOne.value)
5656

57-
// mutate count.value, should trigger onTrigger
57+
// muda count.value, deve acionar onTrigger
5858
count.value++
5959
```
6060

61-
`onTrack` and `onTrigger` only work in development mode.
61+
`onTrack` e `onTrigger` só funcionam no modo de desenvolvimento.
6262

6363
## `watchEffect`
6464

65-
To apply and _automatically re-apply_ a side effect based on reactive state, we can use the `watchEffect` function. It runs a function immediately while reactively tracking its dependencies and re-runs it whenever the dependencies are changed.
65+
Para aplicar e _automaticamente reaplicar_ um efeito colateral baseado no estado reativo, podemos usar a função `watchEffect`. Ela executa uma função imediatamente enquanto rastreia de forma reativa suas dependências e a executa novamente sempre que as dependências são alteradas.
6666

6767
```js
6868
const count = ref(0)
6969

7070
watchEffect(() => console.log(count.value))
71-
// -> logs 0
71+
// -> loga 0
7272

7373
setTimeout(() => {
7474
count.value++
75-
// -> logs 1
75+
// -> loga 1
7676
}, 100)
7777
```
7878

79-
### Stopping the Watcher
79+
### Parando o Observador
8080

81-
When `watchEffect` is called during a component's [setup()](composition-api-setup.html) function or [lifecycle hooks](composition-api-lifecycle-hooks.html), the watcher is linked to the component's lifecycle and will be automatically stopped when the component is unmounted.
81+
Quando `watchEffect` é chamado durante a função [setup()](composition-api-setup.html) de um componente ou [gatilhos do ciclo de vida](composition-api-lifecycle-hooks.html), o observador é vinculado ao ciclo de vida do componente e será interrompido automaticamente quando o componente for desmontado.
8282

83-
In other cases, it returns a stop handle which can be called to explicitly stop the watcher:
83+
Em outros casos, ele retorna um manipulador de parada que pode ser chamado para parar explicitamente o observador:
8484

8585
```js
8686
const stop = watchEffect(() => {
8787
/* ... */
8888
})
8989

90-
// later
90+
// depois
9191
stop()
9292
```
9393

94-
### Side Effect Invalidation
94+
### Invalidação de Efeito Colateral
9595

96-
Sometimes the watched effect function will perform asynchronous side effects that need to be cleaned up when it is invalidated (i.e. state changed before the effects can be completed). The effect function receives an `onInvalidate` function that can be used to register an invalidation callback. This invalidation callback is called when:
96+
Às vezes, a função do efeito observado executará efeitos colaterais assíncronos que precisam ser limpos quando forem invalidados (ou seja, estado alterado antes que os efeitos possam ser concluídos). A função de efeito recebe uma função `onInvalidate` que pode ser usada para registrar um _callback_ de invalidação. Esse _callback_ de invalidação é chamado quando:
9797

98-
- the effect is about to re-run
99-
- the watcher is stopped (i.e. when the component is unmounted if `watchEffect` is used inside `setup()` or lifecycle hooks)
98+
- o efeito está prestes a ser executado novamente
99+
- o observador é parado (ou seja, quando o componente é desmontado se `watchEffect` for usado dentro de `setup()` ou gatilhos de ciclo de vida)
100100

101101
```js
102102
watchEffect(onInvalidate => {
103103
const token = performAsyncOperation(id.value)
104104
onInvalidate(() => {
105-
// id has changed or watcher is stopped.
106-
// invalidate previously pending async operation
105+
// id foi alterado ou o observador está parado.
106+
// invalida a operação assíncrona pendente anteriormente
107107
token.cancel()
108108
})
109109
})
110110
```
111111

112-
We are registering the invalidation callback via a passed-in function instead of returning it from the callback because the return value is important for async error handling. It is very common for the effect function to be an async function when performing data fetching:
112+
Estamos registrando o _callback_ de invalidação por meio de uma função passada em vez de retorná-lo do _callback_ porque o valor retornado é importante para o tratamento de erros assíncronos. É muito comum que a função de efeito seja uma função assíncrona ao realizar a requisição de dados:
113113

114114
```js
115115
const data = ref(null)
116116
watchEffect(async onInvalidate => {
117117
onInvalidate(() => {
118118
/* ... */
119-
}) // we register cleanup function before Promise resolves
119+
}) // registramos a função de limpeza antes que a Promise seja resolvida
120120
data.value = await fetchData(props.id)
121121
})
122122
```
123123

124-
An async function implicitly returns a Promise, but the cleanup function needs to be registered immediately before the Promise resolves. In addition, Vue relies on the returned Promise to automatically handle potential errors in the Promise chain.
124+
Uma função assíncrona retorna implicitamente uma Promise, mas a função de limpeza precisa ser registrada imediatamente antes que a Promise seja resolvida. Além disso, o Vue depende da Promise retornada para lidar automaticamente com possíveis erros na cadeia de Promises.
125125

126-
### Effect Flush Timing
126+
### Momento de Limpeza do Efeito
127127

128-
Vue's reactivity system buffers invalidated effects and flushes them asynchronously to avoid unnecessary duplicate invocation when there are many state mutations happening in the same "tick". Internally, a component's `update` function is also a watched effect. When a user effect is queued, it is by default invoked **before** all component `update` effects:
128+
O sistema de reatividade do Vue armazena em _buffer_ os efeitos invalidados e os libera de forma assíncrona para evitar invocação duplicada desnecessária quando há muitas mutações de estado acontecendo no mesmo "tick". Internamente, a função `update` de um componente também é um efeito observado. Quando um efeito de usuário é enfileirado, ele é invocado por padrão **antes** de todos os efeitos de `update` do componente:
129129

130130
```vue
131131
<template>
@@ -149,17 +149,17 @@ export default {
149149
</script>
150150
```
151151

152-
In this example:
152+
Neste exemplo:
153153

154-
- The count will be logged synchronously on initial run.
155-
- When `count` is mutated, the callback will be called **before** the component has updated.
154+
- A contagem será registrada de forma síncrona na execução inicial.
155+
- Quando `count` for modificado, o callback será chamado **antes** de o componente ser atualizado.
156156

157-
In cases where a watcher effect needs to be re-run **after** component updates (i.e. when working with [Template Refs](./composition-api-template-refs.md#watching-template-refs)), we can pass an additional `options` object with the `flush` option (default is `'pre'`):
157+
Nos casos em que um efeito de observador precisa ser executado novamente **após** atualizações de componentes (ou seja, ao trabalhar com [_Refs_ de _Template_](./composition-api-template-refs.md#observando-refs-de-template)), nós podemos passar um objeto `options` adicional com a opção `flush` (o padrão é `'pre'`):
158158

159159
```js
160-
// fire after component updates so you can access the updated DOM
161-
// Note: this will also defer the initial run of the effect until the
162-
// component's first render is finished.
160+
// dispara após atualizações de componentes para que você possa acessar o DOM atualizado
161+
// Nota: isso também adiará a execução inicial do efeito até
162+
// a primeira renderização do componente ser finalizada.
163163
watchEffect(
164164
() => {
165165
/* ... */
@@ -170,23 +170,23 @@ watchEffect(
170170
)
171171
```
172172

173-
The `flush` option also accepts `'sync'`, which forces the effect to always trigger synchronously. This is however inefficient and should be rarely needed.
173+
A opção `flush` também aceita `'sync'`, o que força o efeito a sempre disparar de forma síncrona. No entanto, isso é ineficiente e raramente deve ser necessário.
174174

175-
In Vue >= 3.2.0, `watchPostEffect` and `watchSyncEffect` aliases can also be used to make the code intention more obvious.
175+
No Vue >= 3.2.0, os apelidos `watchPostEffect` e `watchSyncEffect` também podem ser usados ​​para tornar a intenção do código mais óbvia.
176176

177-
### Watcher Debugging
177+
### Depuração do Observador
178178

179-
The `onTrack` and `onTrigger` options can be used to debug a watcher's behavior.
179+
As opções `onTrack` e `onTrigger` podem ser usadas para depurar o comportamento de um observador.
180180

181-
- `onTrack` will be called when a reactive property or ref is tracked as a dependency.
182-
- `onTrigger` will be called when the watcher callback is triggered by the mutation of a dependency.
181+
- `onTrack` será chamado quando uma propriedade reativa ou _ref_ for rastreada como uma dependência.
182+
- `onTrigger` será chamado quando o _callback_ do observador for acionado pela mutação de uma dependência.
183183

184-
Both callbacks will receive a debugger event which contains information on the dependency in question. It is recommended to place a `debugger` statement in these callbacks to interactively inspect the dependency:
184+
Ambos os _callbacks_ receberão um evento depurador que contém informações sobre a dependência em questão. Recomenda-se colocar uma instrução `debugger` nesses _callbacks_ para inspecionar interativamente a dependência:
185185

186186
```js
187187
watchEffect(
188188
() => {
189-
/* side effect */
189+
/* efeito colateral */
190190
},
191191
{
192192
onTrigger(e) {
@@ -196,24 +196,24 @@ watchEffect(
196196
)
197197
```
198198

199-
`onTrack` and `onTrigger` only work in development mode.
199+
`onTrack` e `onTrigger` só funcionam no modo de desenvolvimento.
200200

201201
## `watch`
202202

203-
The `watch` API is the exact equivalent of the component [watch](computed.html#watchers) property. `watch` requires watching a specific data source and applies side effects in a separate callback function. It also is lazy by default - i.e. the callback is only called when the watched source has changed.
203+
A API `watch` é o equivalente exato da propriedade [watch](computed.html#observadores) do componente. `watch` requer a observação de uma fonte de dados específica e aplica efeitos colaterais em um _callback_ separado. Também é preguiçoso por padrão - ou seja, o _callback_ só é chamado quando a fonte observada foi alterada.
204204

205-
- Compared to [watchEffect](#watcheffect), `watch` allows us to:
205+
- Comparado com [watchEffect](#watcheffect), `watch` nos permite:
206206

207-
- Perform the side effect lazily;
208-
- Be more specific about what state should trigger the watcher to re-run;
209-
- Access both the previous and current value of the watched state.
207+
- Executar o efeito colateral preguiçosamente;
208+
- Ser mais específico sobre qual estado deve acionar o observador para executar novamente;
209+
- Acessar o valor anterior e atual do estado observado.
210210

211-
### Watching a Single Source
211+
### Observando uma Única Fonte
212212

213-
A watcher data source can either be a getter function that returns a value, or directly a `ref`:
213+
Uma fonte de dados do observador pode ser uma função _getter_ que retorna um valor ou diretamente um `ref`:
214214

215-
```js
216-
// watching a getter
215+
``` js
216+
// observando um getter
217217
const state = reactive({ count: 0 })
218218
watch(
219219
() => state.count,
@@ -222,16 +222,16 @@ watch(
222222
}
223223
)
224224

225-
// directly watching a ref
225+
// observando diretamente um ref
226226
const count = ref(0)
227227
watch(count, (count, prevCount) => {
228228
/* ... */
229229
})
230230
```
231231

232-
### Watching Multiple Sources
232+
### Observando Várias Fontes
233233

234-
A watcher can also watch multiple sources at the same time using an array:
234+
Um observador também pode observar várias fontes ao mesmo tempo usando um array:
235235

236236
```js
237237
const firstName = ref('')
@@ -245,7 +245,7 @@ firstName.value = 'John' // logs: ["John", ""] ["", ""]
245245
lastName.value = 'Smith' // logs: ["John", "Smith"] ["John", ""]
246246
```
247247

248-
However, if you are changing both watched sources simultaneously in the same function, the watcher will be executed only once:
248+
No entanto, se você estiver alterando as duas fontes observadas simultaneamente na mesma função, o observador será executado apenas uma vez:
249249

250250
```js{9-13}
251251
setup() {
@@ -266,9 +266,9 @@ setup() {
266266
}
267267
```
268268

269-
Note that multiple synchronous changes will only trigger the watcher once.
269+
Observe que várias alterações síncronas acionarão o observador apenas uma vez.
270270

271-
It is possible to force the watcher to trigger after every change by using the setting `flush: 'sync'`, though that isn't usually recommended. Alternatively, [nextTick](/api/global-api.html#nexttick) can be used to wait for the watcher to run before making further changes. e.g.:
271+
É possível forçar o observador a disparar após cada mudança usando a configuração `flush: 'sync'`, embora isso geralmente não seja recomendado. Como alternativa, [nextTick](/api/global-api.html#nexttick) pode ser usado para aguardar a execução do observador antes de fazer outras alterações. por exemplo.:
272272

273273
```js
274274
const changeValues = async () => {
@@ -278,9 +278,9 @@ const changeValues = async () => {
278278
}
279279
```
280280

281-
### Watching Reactive Objects
281+
### Observando Objetos Reativos
282282

283-
Using a watcher to compare values of an array or object that are reactive requires that it has a copy made of just the values.
283+
Usar um observador para comparar valores de um array ou objeto que são reativos requer que ele tenha uma cópia feita apenas dos valores.
284284

285285
```js
286286
const numbers = reactive([1, 2, 3, 4])
@@ -295,7 +295,7 @@ watch(
295295
numbers.push(5) // logs: [1,2,3,4,5] [1,2,3,4]
296296
```
297297

298-
Attempting to check for changes of properties in a deeply nested object or array will still require the `deep` option to be true:
298+
A tentativa de verificar alterações de propriedades em um objeto ou array profundamente aninhado ainda exigirá que a opção `deep` seja verdadeira:
299299

300300
```js
301301
const state = reactive({
@@ -320,10 +320,10 @@ watch(
320320
{ deep: true }
321321
)
322322

323-
state.attributes.name = 'Alex' // Logs: "deep" "Alex" "Alex"
323+
state.attributes.name = 'Alex' // Loga: "deep" "Alex" "Alex"
324324
```
325325

326-
However, watching a reactive object or array will always return a reference to the current value of that object for both the current and previous value of the state. To fully watch deeply nested objects and arrays, a deep copy of values may be required. This can be achieved with a utility such as [lodash.cloneDeep](https://lodash.com/docs/4.17.15#cloneDeep)
326+
No entanto, observar um objeto ou array reativo sempre retornará uma referência ao valor atual desse objeto para ambos o valor atual e anterior do estado. Para observar completamente objetos e arrays profundamente aninhados, pode ser necessária uma cópia profunda dos valores. Isso pode ser feito com um utilitário como [lodash.cloneDeep](https://lodash.com/docs/4.17.15#cloneDeep)
327327

328328
```js
329329
import _ from 'lodash'
@@ -342,9 +342,9 @@ watch(
342342
}
343343
)
344344

345-
state.attributes.name = 'Alex' // Logs: "Alex" ""
345+
state.attributes.name = 'Alex' // Loga: "Alex" ""
346346
```
347347

348-
### Shared Behavior with `watchEffect`
348+
### Comportamento Compartilhado com `watchEffect`
349349

350-
`watch` shares behavior with [`watchEffect`](#watcheffect) in terms of [manual stoppage](#stopping-the-watcher), [side effect invalidation](#side-effect-invalidation) (with `onInvalidate` passed to the callback as the 3rd argument instead), [flush timing](#effect-flush-timing) and [debugging](#watcher-debugging).
350+
`watch` compartilha comportamento com [`watchEffect`](#watcheffect) em termos de [parada manual](#parando-o-observador), [invalidação de efeito colateral](#invalidacao-de-efeito-colateral) (com `onInvalidate` passado ao _callback_ como o terceiro argumento), [momento de limpeza](#momento-de-limpeza-do-efeito) e [depuração](#depuracao-do-observador).

0 commit comments

Comments
 (0)