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
> This page applies only to Vue 2.x and below, and assumes you've already read the [Reactivity Section](reactivity.md). Please read that section first.
3
+
> Esta página se aplica apenas para o Vue 2.x e inferiores, e assume que você já tenha lido a [Seção de Reatividade](reactivity.md). Por favor leia esta seção primeiro.
4
4
5
-
Due to limitations in JavaScript, there are types of changes that Vue **cannot detect**. However, there are ways to circumvent them to preserve reactivity.
5
+
Devido a limitações no Javascript, existem alguns tipos de mudanças que o Vue **não consegue detectar**. No entanto, existem formas de contorná-las para preservar a reatividade.
6
6
7
-
### For Objects
7
+
### Para *Objects*
8
8
9
-
Vue cannot detect property addition or deletion. Since Vue performs the getter/setter conversion process during instance initialization, a property must be present in the`data`object in order for Vue to convert it and make it reactive. For example:
9
+
Vue não consegue detectar a inserçãoa ou remoção de propriedades. Como o Vue realiza o processo de conversão *getter*/*setter* durante a inicialização da instância, uma propriedade precisa estar presente no objeto`data`para que o Vue possa convertê-lo e torná-lo reativo. Por exemplo:
10
10
11
11
```js
12
12
var vm =newVue({
13
13
data: {
14
14
a:1
15
15
}
16
16
})
17
-
// `vm.a` is now reactive
17
+
// `vm.a` agora é reativa
18
18
19
19
vm.b=2
20
-
// `vm.b` is NOT reactive
20
+
// `vm.b` não é reativa
21
21
```
22
22
23
-
Vue does not allow dynamically adding new root-level reactive properties to an already created instance. However, it's possible to add reactive properties to a nested object using the`Vue.set(object, propertyName, value)` method:
23
+
Vue não permite adicionar dinamicamente novas propriedades nível-raiz (*root-level*) a uma instância já criada. Contudo, é possível adicionar propriedades reativaas a um objeto aninhado usando o método`Vue.set(object, propertyName, value)`:
24
24
25
25
```js
26
26
Vue.set(vm.someObject, 'b', 2)
27
27
```
28
28
29
-
You can also use the `vm.$set` instance method, which is an alias to the global `Vue.set`:
29
+
Você pode também utilizar o método da instância `vm.$set`, que é uma referência ao método global `Vue.set`:
30
30
31
31
```js
32
32
this.$set(this.someObject, 'b', 2)
33
33
```
34
34
35
-
Sometimes you may want to assign a number of properties to an existing object, for example using`Object.assign()`or`_.extend()`. However, new properties added to the object will not trigger changes. In such cases, create a fresh object with properties from both the original object and the mixin object:
35
+
Às vezes você pode querer atribuir mais de uma propriedade para um objeto existente, por exemplo usando`Object.assign()`ou`_.extend()`. No entanto, novas propriedades addicionadas ao objeto não irão acionar mudanças. Nestes casos, crie um objeto novo (*fresh object*) com propriedades de ambos o origial e o alterado (*mixing object*):
36
36
37
37
```js
38
-
//instead of `Object.assign(this.someObject, { a: 1, b: 2 })`
38
+
//invés de `Object.assign(this.someObject, { a: 1, b: 2 })`
Vue cannot detect the following changes to an array:
44
+
Vue não consegue detectar as seguintes mudanças em um *array*:
45
45
46
-
1.When you directly set an item with the index, e.g. `vm.items[indexOfItem] = newValue`
47
-
2.When you modify the length of the array, e.g. `vm.items.length = newLength`
46
+
1.Quando você atribuir diretamente um item através do índice, e.g. `vm.items[indexOfItem] = newValue`
47
+
2.Quando você modifica o comprimento de um *array*, e.g. `vm.items.length = newLength`
48
48
49
-
For example:
49
+
Por exemplo:
50
50
51
51
```js
52
52
var vm =newVue({
53
53
data: {
54
54
items: ['a', 'b', 'c']
55
55
}
56
56
})
57
-
vm.items[1] ='x'//is NOT reactive
58
-
vm.items.length=2//is NOT reactive
57
+
vm.items[1] ='x'//NÃO é reativo
58
+
vm.items.length=2//NÃO é reativo
59
59
```
60
60
61
-
To overcome caveat 1, both of the following will accomplish the same as `vm.items[indexOfItem] = newValue`, but will also trigger state updates in the reactivity system:
61
+
Para contornar a advertência 1, ambas instruções irão fazer o mesmo que `vm.items[indexOfItem] = newValue`, mas irão também acionar as atualizações no estado do sistema reativo:
You can also use the [`vm.$set`](https://vuejs.org/v2/api/#vm-set)instance method, which is an alias for the global `Vue.set`:
73
+
Você pode também usar o método [`vm.$set`](https://vuejs.org/v2/api/#vm-set)da instância que é uma referência ao método global `Vue.set`:
74
74
75
75
```js
76
76
vm.$set(vm.items, indexOfItem, newValue)
77
77
```
78
78
79
-
To deal with caveat 2, you can use`splice`:
79
+
Para lidar com a advertência 2, você pode usar o método`splice`:
80
80
81
81
```js
82
82
vm.items.splice(newLength)
83
83
```
84
84
85
-
## Declaring Reactive Properties
85
+
## Declarando Propriedades Reativas
86
86
87
-
Since Vue doesn't allow dynamically adding root-level reactive properties, you have to initialize component instances by declaring all root-level reactive data properties upfront, even with an empty value:
87
+
Como o Vue não permite inserir propriedades de nível raíz (*root-level*) dinamicamente, você tem que inicializar a instância de um componente declarando todas as propriedades de nível raíz (*root-level*) já inicializadas, mesmo que com valores vazios:
88
88
89
89
```js
90
90
var vm =newVue({
91
91
data: {
92
-
//declare message with an empty value
92
+
//declara message com o valor vazio
93
93
message:''
94
94
},
95
95
template:'<div>{{ message }}</div>'
96
96
})
97
-
//set `message` later
97
+
//atribui valor a `message` posteriormente
98
98
vm.message='Hello!'
99
99
```
100
100
101
-
If you don't declare `message`in the data option, Vue will warn you that the render function is trying to access a property that doesn't exist.
101
+
Se você não declarar a propriedade `message`no objeto data, Vue irá avisar você que a função *render* está tenntando acessar uma propriedade que não exite.
102
102
103
-
There are technical reasons behind this restriction - it eliminates a class of edge cases in the dependency tracking system, and also makes component instances play nicer with type checking systems. But there is also an important consideration in terms of code maintainability: the `data`object is like the schema for your component's state. Declaring all reactive properties upfront makes the component code easier to understand when revisited later or read by another developer.
103
+
Existem razões técnicas por tráz desta restrição - elas eliminam um conjunto de casos extremos no sistema de rastreamento de dependências, além de fazer com que as istâncias dos componenntes funcionem melhor com o sistema de checagem de tipo. Porém há também uma consideração importante em termos de manutennção de código: o objeto `data`funciona como um *schema* para o estado do seu componente. Declarando todas as propriedades reativas inicialmente faz com que o código do componente seja mais fácil de entender quando revisitado posteriormente ou lido po outro desenvolvedor.
104
104
105
-
## Async Update Queue
105
+
## Fila de Atualização Assíncrona (*Async Update Queue*)
106
106
107
-
In case you haven't noticed yet, Vue performs DOM updates **asynchronously**. Whenever a data change is observed, it will open a queue and buffer all the data changes that happen in the same event loop. If the same watcher is triggered multiple times, it will be pushed into the queue only once. This buffered de-duplication is important in avoiding unnecessary calculations and DOM manipulations. Then, in the next event loop "tick", Vue flushes the queue and performs the actual (already de-duped) work. Internally Vue tries native `Promise.then`, `MutationObserver`, and`setImmediate`for the asynchronous queuing and falls back to`setTimeout(fn, 0)`.
107
+
No caso de você não ter notado ainda, Vue realiza atualizações na DOM de forma **assíncrona**. Sempre que uma mudança de dados é observada, é aberta uma fila e armazenado em *buffer* todas as alterações que ocorreram no mesmo ciclo (*event loop*). Se o mesmo observador é acionado muitas vezes, ele será inserido na fila apenas uma vez. Essa eliminação de duplicatas em *buffer* é importante para evitar cálculos e manipulações da DOM desnecessários. Então, no próximo ciclo *"tick"*, Vue limpla a fila e executa o trabalho atual (já desduplicado). Internamente Vue tenta utilizar nativamente `Promise.then`, `MutationObserver`, e`setImmediate`para a enfileiração e retorna para o`setTimeout(fn, 0)`.
108
108
109
-
For example, when you set`vm.someData = 'new value'`, the component will not re-render immediately. It will update in the next "tick", when the queue is flushed. Most of the time we don't need to care about this, but it can be tricky when you want to do something that depends on the post-update DOM state. Although Vue.js generally encourages developers to think in a "data-driven" fashion and avoid touching the DOM directly, sometimes it might be necessary to get your hands dirty. In order to wait until Vue.js has finished updating the DOM after a data change, you can use`Vue.nextTick(callback)`immediately after the data is changed. The callback will be called after the DOM has been updated. For example:
109
+
Por exemplo, quando você atribui`vm.someData = 'new value'`, o componente não irá renderizar novamente de imadiato. Ele irá atualizar no próximo *"tick"*, quando a fila for limpa. Na maioria dos casos nós não precisamos nos preocupar com isso, mas isto pode complicar quando você quer fazer algo que dependa da pós-atualização do estado da DOM (*post-update DOM state*). Contudo Vue.js geralmente encoraja os desenvolvedores a pensar de um modo *"data-driven"* e evitar tocar na DOM diretamente, em alguns casos pode ser necessário sujar as mãos. A fim de esperar até o Vue.js ter finalizado a atualização da DOM depois de uma mudança de *data*, você pode usar`Vue.nextTick(callback)`imediatamente depois da mudança de *data*. O *callback* irá ser chamado depois que a DOM for atualizada. Por exemplo:
110
110
111
111
```html
112
112
<divid="example">{{ message }}</div>
@@ -119,14 +119,14 @@ var vm = new Vue({
119
119
message:'123'
120
120
}
121
121
})
122
-
vm.message='new message'//change data
123
-
vm.$el.textContent==='new message'//false
122
+
vm.message='new message'//altera data
123
+
vm.$el.textContent==='new message'//falso
124
124
Vue.nextTick(function() {
125
-
vm.$el.textContent==='new message'//true
125
+
vm.$el.textContent==='new message'//verdadeiro
126
126
})
127
127
```
128
128
129
-
There is also the `vm.$nextTick()` instance method, which is especially handy inside components, because it doesn't need global `Vue`and its callback's `this` context will be automatically bound to the current component instance:
129
+
Existe também o método da instância `vm.$nextTick()`, que é especialmente eficaz dentro de componentes, pois não precisa da global `Vue`e seus *calback's* e o contexto da variável `this`será automaticamente se limitar ao componente atual:
Since`$nextTick()`returns a promise, you can achieve the same as the above using the new[ES2017 async/await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) syntax:
151
+
Como`$nextTick()`retorna uma *promise*, você pode ter o mesmo efeito acima usando a nova sitaxe[ES2017 async/await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function):
0 commit comments