Skip to content

Commit ab28cc9

Browse files
authored
Merge pull request #150 from leolleocomp/master
docs: Translates guides/reactivity.md to pt-BR
2 parents 188df88 + ac7c91d commit ab28cc9

File tree

1 file changed

+52
-50
lines changed

1 file changed

+52
-50
lines changed

src/guide/reactivity.md

Lines changed: 52 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,21 @@
1-
# Reactivity in Depth
1+
# Aprofundando-se na Reatividade
22

3-
Now it’s time to take a deep dive! One of Vue’s most distinct features is the unobtrusive reactivity system. Models are proxied JavaScript objects. When you modify them, the view updates. It makes state management simple and intuitive, but it’s also important to understand how it works to avoid some common gotchas. In this section, we are going to dig into some of the lower-level details of Vue’s reactivity system.
3+
Agora é o momento de mergulhar fundo! Uma das características mais distintas do Vue é o seu discreto sistema de reatividade. Os modelos de dados são _proxies_ de objetos JavaScript. Quando você os modifica, a _view_ é atualizada. Isso faz com que a administração de estado seja simples e intuitiva, mas também é importante entender como isso funciona para evitar algumas pegadinhas. Nesta seção, vamos nos aprofundar em alguns dos detalhes de baixo nível do sistema de reatividade do Vue.
44

5-
<VideoLesson href="https://www.vuemastery.com/courses/vue-3-reactivity/vue3-reactivity" title="Learn how how reactivity works in depth with Vue Mastery">Watch a free video on Reactivity in Depth on Vue Mastery</VideoLesson>
5+
<VideoLesson href="https://www.vuemastery.com/courses/vue-3-reactivity/vue3-reactivity" title="Aprenda a fundo como a reatividade funciona com o Vue Mastery">Assista um vídeo gratuito sobre Aprofundando-se na Reatividade no Vue Mastery</VideoLesson>
66

7-
## What is Reactivity?
7+
## O Que é Reatividade?
88

9-
This term comes up in programming quite a bit these days, but what do people mean when they say it? Reactivity is a programming paradigm that allows us to adjust to changes in a declarative manner. The canonical example that people usually show, because it’s a great one, is an excel spreadsheet.
9+
Esse termo aparece na programação com uma certa frequência atualmente, mas o que realmente significa quando as pessoas o dizem? Reatividade é um paradigma da programação que permite nos ajustarmos à mudanças de uma maneira declarativa. O exemplo canônico geralmente mostrado, por ser ótimo, é uma planilha do excel.
1010

1111
<video width="550" height="400" controls>
1212
<source src="/images/reactivity-spreadsheet.mp4" type="video/mp4">
13-
Your browser does not support the video tag.
13+
Seu navegador não possui suporte para a tag video.
1414
</video>
1515

16-
If you put the number two in the first cell, and the number 3 in the second and asked for the SUM, the spreadsheet would give it to you. No surprises there. But if you update that first number, the SUM automagically updates too.
16+
Se você colocar o número dois na primeira célula, e o número 3 na segunda e então utilizar o SUM, a planilha te dará o resultado. Até aqui nada demais. Mas se você atualizar o primeiro número, o SUM é automagicamente atualizado.
1717

18-
JavaScript doesn’t usually work like this -- If we were to write something comparable in JavaScript:
18+
O JavaScript, geralmente, não funciona assim -- Se escrevêssemos algo semelhante em Javascript:
1919

2020
```js
2121
var val1 = 2
@@ -31,28 +31,28 @@ val1 = 3
3131
// 5
3232
```
3333

34-
If we update the first value, the sum is not adjusted.
34+
Ao atualizarmos o primeiro valor, a soma não é ajustada.
3535

36-
So how would we do this in JavaScript?
36+
Então, como faríamos isso em JavaScript?
3737

38-
- Detect when there’s a change in one of the values
39-
- Track the function that changes it
40-
- Trigger the function so it can update the final value
38+
- Detecte quando há uma mudança em algum dos valores
39+
- Rastreie a função que o modifica
40+
- Dispare a função de modo que ela possa atualizar o valor final
4141

42-
## How Vue Tracks These Changes
42+
## Como o Vue Rastreia Essas Mudanças
4343

44-
When you pass a plain JavaScript object to an application or component instance as its `data` option, Vue will walk through all of its properties and convert them to [Proxies](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) using a handler with getters and setters. This is an ES6-only feature, but we offer a version of Vue 3 that uses the older `Object.defineProperty` to support IE browsers. Both have the same surface API, but the Proxy version is slimmer and offers improved performance.
44+
Quando você passa um objeto Javascript simples para uma aplicação ou instância de componente, como sua opção `data`, o Vue irá iterar sobre todas as suas propriedades e convertê-las em [Proxies](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) utilizando um _handler_ com getters e setters. Isso é uma _feature_ do ES6, somente, mas nós oferecemos uma versão do Vue 3 que utiliza o `Object.defineProperty` mais antigo, para dar suporte à navegadores IE. Ambas possuem a mesma API, na superfície, mas a versão com Proxy é mais elegante e oferece melhor performance.
4545

4646
<div class="reactivecontent">
47-
<iframe height="500" style="width: 100%;" scrolling="no" title="Proxies and Vue's Reactivity Explained Visually" src="https://codepen.io/sdras/embed/zYYzjBg?height=500&theme-id=light&default-tab=result" frameborder="no" allowtransparency="true" allowfullscreen="true">
48-
See the Pen <a href='https://codepen.io/sdras/pen/zYYzjBg'>Proxies and Vue's Reactivity Explained Visually</a> by Sarah Drasner
49-
(<a href='https://codepen.io/sdras'>@sdras</a>) on <a href='https://codepen.io'>CodePen</a>.
47+
<iframe height="500" style="width: 100%;" scrolling="no" title="Proxies e a Reatividade do Vue Explicados Visualmente" src="https://codepen.io/sdras/embed/zYYzjBg?height=500&theme-id=light&default-tab=result" frameborder="no" allowtransparency="true" allowfullscreen="true">
48+
Veja o Pen <a href='https://codepen.io/sdras/pen/zYYzjBg'>Proxies e a Reatividade do Vue Explicados Visualmente</a> por Sarah Drasner
49+
(<a href='https://codepen.io/sdras'>@sdras</a>) em <a href='https://codepen.io'>CodePen</a>.
5050
</iframe>
5151
</div>
5252

53-
That was rather quick and requires some knowledge of [Proxies](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) to understand! So let’s dive in a bit. There’s a lot of literature on Proxies, but what you really need to know is that a **Proxy is an object that encases another object or function and allows you to intercept it.**
53+
A explicação anterior foi breve e requer algum conhecimento de [Proxies](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) para ser entendida! Então vamos nos aprofundar um pouco. Há muita literatura sobre Proxies, mas o que você realmente precisa saber é que um **Proxy é um objeto que encapsula um outro objeto ou função e permite que você o intercepte.**
5454

55-
We use it like this: `new Proxy(target, handler)`
55+
Nós o utilizamos assim: `new Proxy(target, handler)`
5656

5757
```js
5858
const dinner = {
@@ -71,7 +71,7 @@ console.log(proxy.meal)
7171
// tacos
7272
```
7373

74-
Ok, so far, we’re just wrapping that object and returning it. Cool, but not that useful yet. But watch this, we can also intercept this object while we wrap it in the Proxy. This interception is called a trap.
74+
Ok, até agora, estamos apenas encapsulando o objeto e o retornando. Legal, mas ainda não tão útil. Mas observe isso, nós também podemos interceptar esse objeto enquanto temos ele encapsulado no Proxy. Essa interceptação é chamada de armadilha (_trap_).
7575

7676
```js
7777
const dinner = {
@@ -80,21 +80,21 @@ const dinner = {
8080

8181
const handler = {
8282
get(target, prop) {
83-
console.log('intercepted!')
83+
console.log(‘interceptado!)
8484
return target[prop]
8585
}
8686
}
8787

8888
const proxy = new Proxy(dinner, handler)
8989
console.log(proxy.meal)
9090

91-
// intercepted!
91+
// interceptado!
9292
// tacos
9393
```
9494

95-
Beyond a console log, we could do anything here we wish. We could even _not_ return the real value if we wanted to. This is what makes Proxies so powerful for creating APIs.
95+
Indo além de um `console.log`, nós poderíamos fazer aqui qualquer coisa que desejássemos. Poderíamos até mesmo _não_ retornar o valor real se quiséssemos. Isso é o que torna os Proxies tão poderosos para a criação de APIs.
9696

97-
Furthermore, there’s another feature Proxies offer us. Rather than just returning the value like this: `target[prop]`, we could take this a step further and use a feature called `Reflect`, which allows us to do proper `this` binding. It looks like this:
97+
Além disso, há uma outra _feature_ que os Proxies nos oferecem. Ao invés de apenas retornar valores como esse: `target[prop]`, nós poderíamos levar isso um passo adiante e usar uma _feature_ chamada `Reflect`, que nos permite fazer a interligação apropriada do `this`. Isso leva à algo parecido com isso:
9898

9999
```js{7}
100100
const dinner = {
@@ -110,10 +110,11 @@ const handler = {
110110
const proxy = new Proxy(dinner, handler)
111111
console.log(proxy.meal)
112112
113+
// interceptado!
113114
// tacos
114115
```
115116

116-
We mentioned before that in order to have an API that updates a final value when something changes, we’re going to have to set new values when something changes. We do this in the handler, in a function called `track`, where we pass in the `target` and `key`.
117+
Nós mencionamos antes que para ter uma API que atualiza o valor final quando algo é modificado, vamos precisar configurar novos valores quando alguma coisa muda. Nós fazemos isso no _handler_, em uma função chamada `track`, onde passamos os parâmetros `target` e `key`.
117118

118119
```js{7}
119120
const dinner = {
@@ -130,10 +131,11 @@ const handler = {
130131
const proxy = new Proxy(dinner, handler)
131132
console.log(proxy.meal)
132133
134+
// interceptado!
133135
// tacos
134136
```
135137

136-
Finally, we also set new values when something changes. For this, we’re going to set the changes on our new proxy, by triggering those changes:
138+
Finalmente, nós também configuramos novos valores quando alguma coisa muda. Para isso, vamos configurar as mudanças no nosso novo Proxy, disparando essas mudanças:
137139

138140
```js
139141
const dinner = {
@@ -154,22 +156,23 @@ const handler = {
154156
const proxy = new Proxy(dinner, handler)
155157
console.log(proxy.meal)
156158

159+
// interceptado!
157160
// tacos
158161
```
159162

160-
Remember this list from a few paragraphs ago? Now we have some answers to how Vue handles these changes:
163+
Lembra-se desta lista de alguns parágrafos atrás? Agora nós temos algumas respostas sobre como o Vue manipula essas mudanças:
161164

162-
- <strike>Detect when there’s a change in one of the values</strike>: we no longer have to do this, as Proxies allow us to intercept it
163-
- **Track the function that changes it**: We do this in a getter within the proxy, called `effect`
164-
- **Trigger the function so it can update the final value**: We do in a setter within the proxy, called `trigger`
165+
- <strike>Detecte quando há uma mudança em algum dos valores</strike>: não precisamos mais fazer isso, uma vez que os Proxies nos permitem interceptar essas mudanças
166+
- **Rastreie a função que o modifica**: Nós fazemos isso em um getter dentro do proxy, chamado `effect`
167+
- **Dispare a função de modo que ela possa atualizar o valor final**: Nós fazemos isso em um setter dentro do proxy, chamado `trigger`
165168

166-
The proxied object is invisible to the user, but under the hood they enable Vue to perform dependency-tracking and change-notification when properties are accessed or modified. As of Vue 3, our reactivity is now available in a [separate package](https://github.com/vuejs/vue-next/tree/master/packages/reactivity). One caveat is that browser consoles format differently when converted data objects are logged, so you may want to install [vue-devtools](https://github.com/vuejs/vue-devtools) for a more inspection-friendly interface.
169+
O objeto com o _proxy_ aplicado é invisível para o usuário, mas por baixo dos panos ele possibilita que o Vue faça o rastreamento-de-dependência (_dependency-tracking_) e a notificação-de-mudança (_change-notification_) quando propriedades são acessadas ou modificadas. A partir do Vue 3, nossa reatividade está agora disponível em um [pacote separado](https://github.com/vuejs/vue-next/tree/master/packages/reactivity). Um problema é que o _console_ de navegadores formatam diferentemente quando objetos de dados convertidos são registrados no _log_, então pode ser que você queria instalar o [vue-devtools](https://github.com/vuejs/vue-devtools) para uma interface mais amigável à inspeção.
167170

168-
### Proxied Objects
171+
### Objetos com Proxy Aplicado
169172

170-
Vue internally tracks all objects that have been made reactive, so it always returns the same proxy for the same object.
173+
O Vue rastreia internamente todos os objetos que foram transformados em reativos, então ele sempre retorna o mesmo proxy de um mesmo objeto.
171174

172-
When a nested object is accessed from a reactive proxy, that object is _also_ converted into a proxy before being returned:
175+
Quando um objeto aninhado é acessado através de um proxy reativo, esse objeto é _também_ convertido em um proxy antes de ser retornado:
173176

174177
```js
175178
const handler = {
@@ -186,9 +189,9 @@ const handler = {
186189
}
187190
```
188191

189-
### Proxy vs. original identity
192+
### Proxy vs. Identidade Original
190193

191-
The use of Proxy does introduce a new caveat to be aware with: the proxied object is not equal to the original object in terms of identity comparison (`===`). For example:
194+
O uso do Proxy de fato introduz um novo empecilho a ser considerado: o objeto com o proxy aplicado não é igual ao objeto original em termos de comparação de identidade (`===`). Por exemplo:
192195

193196
```js
194197
const obj = {}
@@ -197,32 +200,31 @@ const wrapped = new Proxy(obj, handlers)
197200
console.log(obj === wrapped) // false
198201
```
199202

200-
The original and the wrapped version will behave the same in most cases, but be aware that they will fail
201-
operations that rely on strong identity comparisons, such as `.filter()` or `.map()`. This caveat is unlikely to come up when using the options API, because all reactive state is accessed from `this` and guaranteed to already be proxies.
203+
A versão original e a versão encapsulada se comportarão da mesma forma na maioria dos casos, mas esteja ciente de que elas irão falhar em operações que dependem de comparações fortes de identidade, como `.filter()` ou `.map()`. Esse empecilho tem pouca chance de ocorrer quando a API de opções estiver sendo utilizada, porque todo o estado reativo é acessado a partir do `this` e é garantido que já sejam _proxies_.
202204

203-
However, when using the composition API to explicitly create reactive objects, the best practice is to never hold a reference to the original raw object and only work with the reactive version:
205+
Entretanto, quanto estiver utilizando a API de composição para criar objetos reativos explicitamente, a melhor prática é a de nunca guardar uma referência para o puro objeto original e trabalhar somente com a versão reativa:
204206

205207
```js
206208
const obj = reactive({
207209
count: 0
208-
}) // no reference to original
210+
}) // nenhuma referência ao original
209211
```
210212

211-
## Watchers
213+
## Observadores
212214

213-
Every component instance has a corresponding watcher instance, which records any properties "touched" during the component’s render as dependencies. Later on when a dependency’s setter is triggered, it notifies the watcher, which in turn causes the component to re-render.
215+
Toda instância de componente tem uma instância de observador correspondente, que registra quaisquer propriedades "tocadas" durante a renderização do componente como dependências. Depois, quando um setter de uma dependência é disparado, ele notifica o observador, que por sua vez faz o componente re-renderizar.
214216

215217
<div class="reactivecontent">
216-
<iframe height="500" style="width: 100%;" scrolling="no" title="Second Reactivity with Proxies in Vue 3 Explainer" src="https://codepen.io/sdras/embed/GRJZddR?height=500&theme-id=light&default-tab=result" frameborder="no" allowtransparency="true" allowfullscreen="true">
217-
See the Pen <a href='https://codepen.io/sdras/pen/GRJZddR'>Second Reactivity with Proxies in Vue 3 Explainer</a> by Sarah Drasner
218-
(<a href='https://codepen.io/sdras'>@sdras</a>) on <a href='https://codepen.io'>CodePen</a>.
218+
<iframe height="500" style="width: 100%;" scrolling="no" title="Explicação da Segunda Reatividade com Proxies no Vue 3" src="https://codepen.io/sdras/embed/GRJZddR?height=500&theme-id=light&default-tab=result" frameborder="no" allowtransparency="true" allowfullscreen="true">
219+
Veja o Pen <a href='https://codepen.io/sdras/pen/GRJZddR'>Explicação da Segunda Reatividade com Proxies no Vue 3</a> por Sarah Drasner
220+
(<a href='https://codepen.io/sdras'>@sdras</a>) no <a href='https://codepen.io'>CodePen</a>.
219221
</iframe>
220222
</div>
221223

222-
When you pass an object to a component instance as data, Vue converts it to a proxy. This proxy enables Vue to perform dependency-tracking and change-notification when properties are accessed or modified. Each property is considered a dependency.
224+
Quando você passa um objeto para uma instância de um componente como _data_, o Vue o converte em um proxy. Esse proxy permite ao Vue realizar o rastreamento-de-dependência (_dependency-tracking_) e a notificação-de-mudança (_change-notification_), quando as propriedades são acessadas ou modificadas. Cada propriedade é considerada uma dependência.
223225

224-
After the first render, a component would have tracked a list of dependencies &mdash; the properties it accessed during the render. Conversely, the component becomes a subscriber to each of these properties. When a proxy intercepts a set operation, the property will notify all of its subscribed components to re-render.
226+
Após a primeira renderização, um componente teria rastreado uma lista de dependências &mdash; as propriedades que acessou durante a renderização. Inversamente, o componente se torna um assinante de cada uma dessas propriedades. Quando um proxy intercepta uma operação _set_, a propriedade notificará cada um de seus componentes assinantes para re-renderizarem.
225227

226-
[//]: # 'TODO: Insert diagram'
228+
[//]: # 'TODO: Inserir diagrama'
227229

228-
> If you are using Vue 2.x and below, you may be interested in some of the change detection caveats that exist for those versions, [explored in more detail here](change-detection.md).
230+
> Se você está utilizando Vue v2.x ou mais antigo, pode estar interessado em alguns empecilhos da detecção de mudanças que existem nessas versões, [explorados em mais detalhes aqui](change-detection.md).

0 commit comments

Comments
 (0)