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
To create a reactive state from a JavaScript object, we can use a`reactive` method:
5
+
Para criar um estado reativo a partir de um objeto JavaScript, podemos usar o método`reactive`:
6
6
7
7
```js
8
8
import { reactive } from'vue'
9
9
10
-
//reactive state
10
+
//estado reativo
11
11
conststate=reactive({
12
12
count:0
13
13
})
14
14
```
15
15
16
-
`reactive`is the equivalent of the `Vue.observable()`API in Vue 2.x, renamed to avoid confusion with RxJS observables. Here, the returned state is a reactive object. The reactive conversion is "deep" - it affects all nested properties of the passed object.
16
+
`reactive`é equivalente à API `Vue.observable()`do Vue 2.x, renomeado para evitar confusões com os `Observables` do RxJS. Aqui, o estado retornado é um objeto reativo. A conversão reativa é "profunda" - ela afeta todas as propriedades aninhadas do objeto passado.
17
17
18
-
The essential use case for reactive state in Vue is that we can use it during render. Thanks to dependency tracking, the view automatically updates when reactive state changes.
18
+
O caso de uso essencial para o estado reativo no Vue é que podemos usá-lo durante a renderização. Graças ao rastreamento de dependência, a exibição é atualizada automaticamente quando o estado reativo muda.
19
19
20
-
This is the very essence of Vue's reactivity system. When you return an object from`data()`in a component, it is internally made reactive by`reactive()`. The template is compiled into a [render function](render-function.html)that makes use of these reactive properties.
20
+
Esta é a própria essência do sistema de reatividade do Vue. Quando você retorna um objeto de`data()`em um componente, ele é tornado reativo internamente pelo`reactive()`. O _template_ é compilado em uma [função de renderização](render-function.html)que faz uso dessas propriedades reativas.
21
21
22
-
You can learn more about`reactive`in the [Basic Reactivity API's](../api/basic-reactivity.html) section
22
+
Você pode aprender mais sobre`reactive`na seção [Básico da API de Reatividade](../api/basic-reactivity.html)
23
23
24
-
## Creating Standalone Reactive Values as`refs`
24
+
## Criação de Valores Reativos Avulsos como`refs`
25
25
26
-
Imagine the case where we have a standalone primitive value (for example, a string) and we want to make it reactive. Of course, we could make an object with a single property equal to our string, and pass it to `reactive`. Vue has a method that will do the same for us - it's a`ref`:
26
+
Imagine o caso em que temos um valor primitivo avulso (por exemplo, uma string) e queremos torná-la reativa. Claro, poderíamos fazer um objeto com uma única propriedade igual à nossa string e passá-la para `reactive`. Vue tem um método que fará o mesmo para nós - ele é o`ref`:
27
27
28
28
```js
29
29
import { ref } from'vue'
30
30
31
31
constcount=ref(0)
32
32
```
33
33
34
-
`ref`will return a reactive and mutable object that serves as a reactive **ref**erence to the internal value it is holding - that's where the name comes from. This object contains the only one property named`value`:
34
+
`ref`retornará um objeto reativo e mutável que serve como uma **ref**erência reativa para o valor interno que está mantendo - é daí que vem o seu nome. Este objeto contém uma única propriedade chamada`value`:
35
35
36
36
```js
37
37
import { ref } from'vue'
@@ -43,15 +43,15 @@ count.value++
43
43
console.log(count.value) // 1
44
44
```
45
45
46
-
### Ref Unwrapping
46
+
### Ref Desempacotada
47
47
48
-
When a ref is returned as a property on the render context (the object returned from[setup()](composition-api-setup.html)) and accessed in the template, it automatically unwraps to the inner value. There is no need to append `.value`in the template:
48
+
Quando um `ref` é retornado como uma propriedade no contexto de renderização (o objeto retornado de[setup()](composition-api-setup.html)) e acessado no _template_, ele se desempacota automaticamente para o valor interno. Não há necessidade de anexar `.value`no _template_:
@@ -68,9 +68,9 @@ When a ref is returned as a property on the render context (the object returned
68
68
</script>
69
69
```
70
70
71
-
### Access in Reactive Objects
71
+
### Acesso em Objetos Reativos
72
72
73
-
When a`ref`is accessed or mutated as a property of a reactive object, it automatically unwraps to the inner value so it behaves like a normal property:
73
+
Quando um`ref`é acessado ou alterado como uma propriedade de um objeto reativo, ele se desempacota automaticamente para o valor interno para que se comporte como uma propriedade normal:
74
74
75
75
```js
76
76
constcount=ref(0)
@@ -84,7 +84,7 @@ state.count = 1
84
84
console.log(count.value) // 1
85
85
```
86
86
87
-
If a new ref is assigned to a property linked to an existing ref, it will replace the old ref:
87
+
Se uma nova `ref` for atribuída à uma propriedade vinculada à uma `ref` existente, ela substituirá a antiga ref:
88
88
89
89
```js
90
90
constotherCount=ref(2)
@@ -94,60 +94,60 @@ console.log(state.count) // 2
94
94
console.log(count.value) // 1
95
95
```
96
96
97
-
Ref unwrapping only happens when nested inside a reactive `Object`. There is no unwrapping performed when the ref is accessed from an`Array`or a native collection type like[`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map):
97
+
O desempacotamento de um `ref` só acontece quando aninhado dentro de um `Object` reativo. Não há desempacotamento executado quando o `ref` é acessado de um`Array`ou um tipo de coleção nativo como[`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map):
98
98
99
99
```js
100
-
constbooks=reactive([ref('Vue 3 Guide')])
101
-
//need .value here
100
+
constbooks=reactive([ref('Guia do Vue 3')])
101
+
//precisa usar .value aqui
102
102
console.log(books[0].value)
103
103
104
104
constmap=reactive(newMap([['count', ref(0)]]))
105
-
//need .value here
105
+
//precisa usar .value aqui
106
106
console.log(map.get('count').value)
107
107
```
108
108
109
-
## Destructuring Reactive State
109
+
## Desestruturar Estado Reativo
110
110
111
-
When we want to use a few properties of the large reactive object, it could be tempting to use [ES6 destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)to get properties we want:
111
+
Quando queremos usar algumas propriedades do grande objeto reativo, pode ser tentador usar [desestruturação do ES6](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)para obter as propriedades que desejamos:
112
112
113
113
```js
114
114
import { reactive } from'vue'
115
115
116
116
constbook=reactive({
117
-
author:'Vue Team',
117
+
author:'Equipe Vue',
118
118
year:'2020',
119
-
title:'Vue 3 Guide',
120
-
description:'You are reading this book right now ;)',
121
-
price:'free'
119
+
title:'Guia do Vue 3',
120
+
description:'Você está lendo esta documentação agora ;)',
121
+
price:'grátis'
122
122
})
123
123
124
124
let { author, title } = book
125
125
```
126
126
127
-
Unfortunately, with such a destructuring the reactivity for both properties would be lost. For such a case, we need to convert our reactive object to a set of refs. These refs will retain the reactive connection to the source object:
127
+
Infelizmente, com tal desestruturação, a reatividade para ambas as propriedades seria perdida. Para tal, precisamos converter nosso objeto reativo em um conjunto de refs. Esses refs manterão a conexão reativa com o objeto de origem:
128
128
129
129
```js
130
130
import { reactive, toRefs } from'vue'
131
131
132
132
constbook=reactive({
133
-
author:'Vue Team',
133
+
author:'Equipe Vue',
134
134
year:'2020',
135
-
title:'Vue 3 Guide',
136
-
description:'You are reading this book right now ;)',
137
-
price:'free'
135
+
title:'Guia do Vue 3',
136
+
description:'Você está lendo esta documentação agora ;)',
137
+
price:'grátis'
138
138
})
139
139
140
140
let { author, title } =toRefs(book)
141
141
142
-
title.value='Vue 3 Detailed Guide'//we need to use .value as title is a ref now
143
-
console.log(book.title) // 'Vue 3 Detailed Guide'
142
+
title.value='Guia detalhado do Vue 3'//precisamos usar .value porque `title` é uma `ref` agora
143
+
console.log(book.title) // 'Guia detalhado do Vue 3'
144
144
```
145
145
146
-
You can learn more about`refs`in the [Refs API](../api/refs-api.html#ref) section
146
+
Você pode aprender mais sobre`refs`na seção [API de Refs](../api/refs-api.html#ref)
Sometimes we want to track changes of the reactive object (`ref`or `reactive`) but we also want prevent changing it from a certain place of the application. For example, when we have a [provided](component-provide-inject.html) reactive object, we want to prevent mutating it where it's injected. To do so, we can create a readonly proxy to the original object:
150
+
Às vezes, queremos rastrear as alterações do objeto reativo (`ref`ou`reactive`), mas também queremos evitar alterá-lo de um determinado local do aplicativo. Por exemplo, quando temos um objeto reativo [provido](component-provide-inject.html), queremos evitar a sua mutação onde ele é injetado. Para fazer isso, podemos criar um _proxy_ somente leitura (readonly) para o objeto original:
0 commit comments