Skip to content

Commit 9777afe

Browse files
committed
traducao ate a 109
1 parent 8e1c7a2 commit 9777afe

File tree

1 file changed

+30
-29
lines changed

1 file changed

+30
-29
lines changed

src/guide/change-detection.md

Lines changed: 30 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,64 +1,64 @@
1-
# Change Detection Caveats in Vue 2
1+
# Advertência de Alterações Detectadas no Vue 2
22

3-
> 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.
44
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.
66

7-
### For Objects
7+
### Para *Objects*
88

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:
1010

1111
```js
1212
var vm = new Vue({
1313
data: {
1414
a: 1
1515
}
1616
})
17-
// `vm.a` is now reactive
17+
// `vm.a` agora é reativa
1818

1919
vm.b = 2
20-
// `vm.b` is NOT reactive
20+
// `vm.b` não é reativa
2121
```
2222

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)`:
2424

2525
```js
2626
Vue.set(vm.someObject, 'b', 2)
2727
```
2828

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`:
3030

3131
```js
3232
this.$set(this.someObject, 'b', 2)
3333
```
3434

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*):
3636

3737
```js
38-
// instead of `Object.assign(this.someObject, { a: 1, b: 2 })`
38+
// invés de `Object.assign(this.someObject, { a: 1, b: 2 })`
3939
this.someObject = Object.assign({}, this.someObject, { a: 1, b: 2 })
4040
```
4141

42-
### For Arrays
42+
### Para *Arrays*
4343

44-
Vue cannot detect the following changes to an array:
44+
Vue não consegue detectar as seguintes mudanças em um *array*:
4545

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`
4848

49-
For example:
49+
Por exemplo:
5050

5151
```js
5252
var vm = new Vue({
5353
data: {
5454
items: ['a', 'b', 'c']
5555
}
5656
})
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
5959
```
6060

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:
6262

6363
```js
6464
// Vue.set
@@ -70,42 +70,43 @@ Vue.set(vm.items, indexOfItem, newValue)
7070
vm.items.splice(indexOfItem, 1, newValue)
7171
```
7272

73-
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`:
7474

7575
```js
7676
vm.$set(vm.items, indexOfItem, newValue)
7777
```
7878

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`:
8080

8181
```js
8282
vm.items.splice(newLength)
8383
```
8484

85-
## Declaring Reactive Properties
85+
## Declarando Propriedades Reativas
8686

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:
8888

8989
```js
9090
var vm = new Vue({
9191
data: {
92-
// declare message with an empty value
92+
// declara message com o valor vazio
9393
message: ''
9494
},
9595
template: '<div>{{ message }}</div>'
9696
})
97-
// set `message` later
97+
// atribui valor a `message` posteriormente
9898
vm.message = 'Hello!'
9999
```
100100

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.
102102

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.
104104

105-
## Async Update Queue
105+
## Fila de Atualização Assíncrona (*Async Update Queue*)
106106

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)`.
108108

109+
Por exemplo, quando você atribui `vm.someData = 'new value'`, o componente não irá renderizar novamente de imadiato.
109110
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:
110111

111112
```html

0 commit comments

Comments
 (0)