You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/guide/reactivity.md
+52-50Lines changed: 52 additions & 50 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,21 +1,21 @@
1
-
# Reactivity in Depth
1
+
# Aprofundando-se na Reatividade
2
2
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.
4
4
5
-
<VideoLessonhref="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
+
<VideoLessonhref="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>
6
6
7
-
## What is Reactivity?
7
+
## O Que é Reatividade?
8
8
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.
Seu navegador não possui suporte para a tag video.
14
14
</video>
15
15
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.
17
17
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:
19
19
20
20
```js
21
21
var val1 =2
@@ -31,28 +31,28 @@ val1 = 3
31
31
// 5
32
32
```
33
33
34
-
If we update the first value, the sum is not adjusted.
34
+
Ao atualizarmos o primeiro valor, a soma não é ajustada.
35
35
36
-
So how would we do this in JavaScript?
36
+
Então, como faríamos isso em JavaScript?
37
37
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
41
41
42
-
## How Vue Tracks These Changes
42
+
## Como o Vue Rastreia Essas Mudanças
43
43
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.
45
45
46
46
<divclass="reactivecontent">
47
-
<iframeheight="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
+
<iframeheight="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>.
50
50
</iframe>
51
51
</div>
52
52
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.**
54
54
55
-
We use it like this: `new Proxy(target, handler)`
55
+
Nós o utilizamos assim: `new Proxy(target, handler)`
56
56
57
57
```js
58
58
constdinner= {
@@ -71,7 +71,7 @@ console.log(proxy.meal)
71
71
// tacos
72
72
```
73
73
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_).
75
75
76
76
```js
77
77
constdinner= {
@@ -80,21 +80,21 @@ const dinner = {
80
80
81
81
consthandler= {
82
82
get(target, prop) {
83
-
console.log('intercepted!')
83
+
console.log(‘interceptado!’)
84
84
return target[prop]
85
85
}
86
86
}
87
87
88
88
constproxy=newProxy(dinner, handler)
89
89
console.log(proxy.meal)
90
90
91
-
//intercepted!
91
+
//interceptado!
92
92
// tacos
93
93
```
94
94
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.
96
96
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:
98
98
99
99
```js{7}
100
100
const dinner = {
@@ -110,10 +110,11 @@ const handler = {
110
110
const proxy = new Proxy(dinner, handler)
111
111
console.log(proxy.meal)
112
112
113
+
// interceptado!
113
114
// tacos
114
115
```
115
116
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`.
117
118
118
119
```js{7}
119
120
const dinner = {
@@ -130,10 +131,11 @@ const handler = {
130
131
const proxy = new Proxy(dinner, handler)
131
132
console.log(proxy.meal)
132
133
134
+
// interceptado!
133
135
// tacos
134
136
```
135
137
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:
137
139
138
140
```js
139
141
constdinner= {
@@ -154,22 +156,23 @@ const handler = {
154
156
constproxy=newProxy(dinner, handler)
155
157
console.log(proxy.meal)
156
158
159
+
// interceptado!
157
160
// tacos
158
161
```
159
162
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:
161
164
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`
165
168
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.
167
170
168
-
### Proxied Objects
171
+
### Objetos com Proxy Aplicado
169
172
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.
171
174
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:
173
176
174
177
```js
175
178
consthandler= {
@@ -186,9 +189,9 @@ const handler = {
186
189
}
187
190
```
188
191
189
-
### Proxy vs. original identity
192
+
### Proxy vs. Identidade Original
190
193
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:
192
195
193
196
```js
194
197
constobj= {}
@@ -197,32 +200,31 @@ const wrapped = new Proxy(obj, handlers)
197
200
console.log(obj === wrapped) // false
198
201
```
199
202
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_.
202
204
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:
204
206
205
207
```js
206
208
constobj=reactive({
207
209
count:0
208
-
}) //no reference to original
210
+
}) //nenhuma referência ao original
209
211
```
210
212
211
-
## Watchers
213
+
## Observadores
212
214
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.
214
216
215
217
<divclass="reactivecontent">
216
-
<iframeheight="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
+
<iframeheight="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>.
219
221
</iframe>
220
222
</div>
221
223
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.
223
225
224
-
After the first render, a component would have tracked a list of dependencies —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 —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.
225
227
226
-
[//]: #'TODO: Insert diagram'
228
+
[//]: #'TODO: Inserir diagrama'
227
229
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