|
1 |
| -# Data |
| 1 | +# Dados |
2 | 2 |
|
3 | 3 | ## data
|
4 | 4 |
|
5 |
| -- **Type:** `Function` |
| 5 | +- **Tipo:** `Function` |
6 | 6 |
|
7 |
| -- **Details:** |
| 7 | +- **Detalhes:** |
8 | 8 |
|
9 |
| - The function that returns a data object for the component instance. In `data`, we don't recommend to observe objects with their own stateful behavior like browser API objects and prototype properties. A good idea would be to have here just a plain object that represents component data. |
| 9 | + A função que retorna um objeto de dados para a instância do componente. Em `data`, não recomendamos observar objetos com seu próprio comportamento com estado, como objetos de API do navegador e propriedades _prototype_. Uma boa ideia seria ter aqui apenas um objeto simples que representa os dados do componente. |
10 | 10 |
|
11 |
| - Once observed, you can no longer add reactive properties to the root data object. It is therefore recommended to declare all root-level reactive properties upfront, before creating the instance. |
| 11 | + Uma vez observado, você não pode mais adicionar propriedades reativas ao objeto de dados raiz. Portanto, é recomendável declarar antecipadamente todas as propriedades reativas de nível raiz, antes da criação da instância. |
12 | 12 |
|
13 |
| - After the instance is created, the original data object can be accessed as `vm.$data`. The component instance also proxies all the properties found on the data object, so `vm.a` will be equivalent to `vm.$data.a`. |
| 13 | + Depois da instância ser criada, o objeto de dados original pode ser acessado como `vm.$data`. A instância do componente também faz _proxy_ de todas as propriedades encontradas no objeto de dados, então `vm.a` será equivalente a `vm.$data.a`. |
14 | 14 |
|
15 |
| - Properties that start with `_` or `$` will **not** be proxied on the component instance because they may conflict with Vue's internal properties and API methods. You will have to access them as `vm.$data._property`. |
| 15 | + Propriedades que comecem com `_` ou `$` **não** terão seu _proxy_ feito na instância do componente porque eles podem entrar em conflito com as propriedades internas do Vue ou métodos de API. Você terá que acessá-las como `vm.$data._property`. |
16 | 16 |
|
17 |
| -- **Example:** |
| 17 | +- **Exemplo:** |
18 | 18 |
|
19 | 19 | ```js
|
20 |
| - // direct instance creation |
| 20 | + // Criação direta de instância |
21 | 21 | const data = { a: 1 }
|
22 | 22 |
|
23 |
| - // The object is added to a component instance |
| 23 | + // O objeto é adicionado a uma instância do componente |
24 | 24 | const vm = Vue.createApp({
|
25 | 25 | data() {
|
26 | 26 | return data
|
|
30 | 30 | console.log(vm.a) // => 1
|
31 | 31 | ```
|
32 | 32 |
|
33 |
| - Note that if you use an arrow function with the `data` property, `this` won't be the component's instance, but you can still access the instance as the function's first argument: |
| 33 | + Note que se usar uma *arrow function* com a propriedade `data`,` this` não será a instância do componente, mas você poderá continuar tendo acesso à instância através do argumento da função: |
34 | 34 |
|
35 | 35 | ```js
|
36 | 36 | data: vm => ({ a: vm.myProp })
|
37 | 37 | ```
|
38 | 38 |
|
39 |
| -- **See also:** [Reactivity in Depth](../guide/reactivity.html) |
| 39 | +- **Ver também:** [Reatividade em profundidade](../guide/reactivity.html) |
40 | 40 |
|
41 | 41 | ## props
|
42 | 42 |
|
43 |
| -- **Type:** `Array<string> | Object` |
| 43 | +- **Tipo:** `Array<string> | Object` |
44 | 44 |
|
45 |
| -- **Details:** |
| 45 | +- **Detalhes:** |
46 | 46 |
|
47 |
| - A list/hash of attributes that are exposed to accept data from the parent component. It has an Array-based simple syntax and an alternative Object-based syntax that allows advanced configurations such as type checking, custom validation and default values. |
| 47 | + Uma lista/*hash* de atributos que são expostos para aceitar dados do componente pai. Possui tanto uma sintaxe simples baseada em Array como, alternativamente, uma sintaxe baseada em Object, que permite configurações avançadas como verificação de tipos, validações personalizadas e valores padrão. |
48 | 48 |
|
49 |
| - With Object-based syntax, you can use following options: |
| 49 | + Com a sintaxe baseada em Object, você pode usar as seguintes opções: |
50 | 50 |
|
51 |
| - - `type`: can be one of the following native constructors: `String`, `Number`, `Boolean`, `Array`, `Object`, `Date`, `Function`, `Symbol`, any custom constructor function or an array of those. Will check if a prop has a given type, and will throw a warning if it doesn't. [More information](../guide/component-props.html#prop-types) on prop types. |
| 51 | + - `type`: pode ser um dos seguintes construtores nativos: `String`, `Number`, `Boolean`, `Array`, `Object`, `Date`, `Function`, `Symbol`, qualquer função construtora personalizada ou um array delas. Irá verificar se um prop tem um determinado tipo, e irá lançar um aviso se não tiver. [Mais informação](../guide/component-props.html#tipos-de-propriedades) em tipos de props. |
52 | 52 | - `default`: `any`
|
53 |
| - Specifies a default value for the prop. If the prop is not passed, this value will be used instead. Object or array defaults must be returned from a factory function. |
| 53 | + Especifica um valor padrão para o prop. Se o prop não é passado, este valor será usado em seu lugar. Valores padrão de tipo Object ou Array devem ser retornados de uma função *factory*. |
54 | 54 | - `required`: `Boolean`
|
55 |
| - Defines if the prop is required. In a non-production environment, a console warning will be thrown if this value is truthy and the prop is not passed. |
| 55 | + Define se o prop é necessário. Em ambiente de não-produção, um aviso de console será lançado se esse valor for verdadeiro e o prop não for passado. |
56 | 56 | - `validator`: `Function`
|
57 |
| - Custom validator function that takes the prop value as the sole argument. In a non-production environment, a console warning will be thrown if this function returns a falsy value (i.e. the validation fails). You can read more about prop validation [here](../guide/component-props.html#prop-validation). |
| 57 | + Função validadora personalizada que usa o valor do prop como único argumento. Exceto em ambiente de produção, um aviso de console será lançado se essa função retornar um valor falso (ou seja, a validação falhar). Pode ler mais sobre validação de prop [aqui](../guide/component-props.html#validacao-de-propriedades). |
58 | 58 |
|
59 |
| -- **Example:** |
| 59 | +- **Exemplo:** |
60 | 60 |
|
61 | 61 | ```js
|
62 | 62 | const app = Vue.createApp({})
|
63 | 63 |
|
64 |
| - // simple syntax |
| 64 | + // sintaxe simples |
65 | 65 | app.component('props-demo-simple', {
|
66 | 66 | props: ['size', 'myMessage']
|
67 | 67 | })
|
68 | 68 |
|
69 |
| - // object syntax with validation |
| 69 | + // sintaxe de objeto com validação |
70 | 70 | app.component('props-demo-advanced', {
|
71 | 71 | props: {
|
72 |
| - // type check |
| 72 | + // verificação de tipo |
73 | 73 | height: Number,
|
74 |
| - // type check plus other validations |
| 74 | + // verificação de tipo com outras validações |
75 | 75 | age: {
|
76 | 76 | type: Number,
|
77 | 77 | default: 0,
|
|
84 | 84 | })
|
85 | 85 | ```
|
86 | 86 |
|
87 |
| -- **See also:** [Props](../guide/component-props.html) |
| 87 | +- **Ver também:** [Propriedades](../guide/component-props.html) |
88 | 88 |
|
89 | 89 | ## computed
|
90 | 90 |
|
91 |
| -- **Type:** `{ [key: string]: Function | { get: Function, set: Function } }` |
| 91 | +- **Tipo:** `{ [key: string]: Function | { get: Function, set: Function } }` |
92 | 92 |
|
93 |
| -- **Details:** |
| 93 | +- **Detalhes:** |
94 | 94 |
|
95 |
| - Computed properties to be mixed into the component instance. All getters and setters have their `this` context automatically bound to the component instance. |
| 95 | + Dados computados a serem combinados na instância do componente. Todos os getters e setters tem o seu contexto `this` vinculado automaticamente à instância do componente. |
96 | 96 |
|
97 |
| - Note that if you use an arrow function with a computed property, `this` won't be the component's instance, but you can still access the instance as the function's first argument: |
| 97 | + Note que se usar *arrow function* com um dado computado, `this` não será a instância do componente, mas você poderá ter acesso a instância através do primeiro argumento da função: |
98 | 98 |
|
99 | 99 | ```js
|
100 | 100 | computed: {
|
101 | 101 | aDouble: vm => vm.a * 2
|
102 | 102 | }
|
103 | 103 | ```
|
104 | 104 |
|
105 |
| - Computed properties are cached, and only re-computed on reactive dependency changes. Note that if a certain dependency is out of the instance's scope (i.e. not reactive), the computed property will **not** be updated. |
| 105 | + Dados computados são cacheados, e apenas re-computados quando dependências reativas mudam. Note que se uma certa dependência está fora do escopo da instância (ex.: não reativa), o dado computado **não** será atualizado. |
106 | 106 |
|
107 |
| -- **Example:** |
| 107 | +- **Exemplo:** |
108 | 108 |
|
109 | 109 | ```js
|
110 | 110 | const app = Vue.createApp({
|
111 | 111 | data() {
|
112 | 112 | return { a: 1 }
|
113 | 113 | },
|
114 | 114 | computed: {
|
115 |
| - // get only |
| 115 | + // apenas get |
116 | 116 | aDouble() {
|
117 | 117 | return this.a * 2
|
118 | 118 | },
|
119 |
| - // both get and set |
| 119 | + // ambos get e set |
120 | 120 | aPlus: {
|
121 | 121 | get() {
|
122 | 122 | return this.a + 1
|
|
135 | 135 | console.log(vm.aDouble) // => 4
|
136 | 136 | ```
|
137 | 137 |
|
138 |
| -- **See also:** [Computed Properties](../guide/computed.html) |
| 138 | +- **Ver também:** [Dados Computados](../guide/computed.html) |
139 | 139 |
|
140 | 140 | ## methods
|
141 | 141 |
|
142 |
| -- **Type:** `{ [key: string]: Function }` |
| 142 | +- **Tipo:** `{ [key: string]: Function }` |
143 | 143 |
|
144 |
| -- **Details:** |
| 144 | +- **Detalhes:** |
145 | 145 |
|
146 |
| - Methods to be mixed into the component instance. You can access these methods directly on the VM instance, or use them in directive expressions. All methods will have their `this` context automatically bound to the component instance. |
| 146 | + Métodos a serem combinados na instância do componente. Você pode acessar esses métodos diretamente na instância VM ou usá-los em expressões de diretiva. Todos os métodos terão o seu contexto `this` automaticamente vinculado à instância do componente. |
147 | 147 |
|
148 |
| - :::tip Note |
149 |
| - Note that **you should not use an arrow function to define a method** (e.g. `plus: () => this.a++`). The reason is arrow functions bind the parent context, so `this` will not be the component instance as you expect and `this.a` will be undefined. |
| 148 | + ::: tip Nota |
| 149 | + Note que **você não deve usar *arrow function* para definir um método** (ex. `plus: () => this.a++`). A razão é que *arrow functions* fazem *bind* do contexto pai, então `this` não será a instância Vue como você está esperando e `this.a` será `undefined`. |
150 | 150 | :::
|
151 | 151 |
|
152 |
| -- **Example:** |
| 152 | +- **Exemplo:** |
153 | 153 |
|
154 | 154 | ```js
|
155 | 155 | const app = Vue.createApp({
|
|
169 | 169 | console.log(vm.a) // => 2
|
170 | 170 | ```
|
171 | 171 |
|
172 |
| -- **See also:** [Event Handling](../guide/events.html) |
| 172 | +- **Ver também:** [Manipulação de Eventos](../guide/events.html) |
173 | 173 |
|
174 | 174 | ## watch
|
175 | 175 |
|
176 |
| -- **Type:** `{ [key: string]: string | Function | Object | Array}` |
| 176 | +- **Tipo:** `{ [key: string]: string | Function | Object | Array}` |
177 | 177 |
|
178 |
| -- **Details:** |
| 178 | +- **Detalhes:** |
179 | 179 |
|
180 |
| - An object where keys are expressions to watch and values are the corresponding callbacks. The value can also be a string of a method name, or an Object that contains additional options. The component instance will call `$watch()` for each entry in the object at instantiation. See [$watch](instance-methods.html#watch) for more information about the `deep`, `immediate` and `flush` options. |
| 180 | + Um objeto onde as chaves são expressões para observar e os valores são os *callbacks* correspondentes. O valor também pode ser uma string de um nome de método ou um Object que contém opções adicionais. A instância do componente chamará `$watch()` para cada entrada no objeto na inicialização. Veja [$watch](instance-methods.html#watch) para mais informações sobre as opções `deep`, `immediate` e `flush`. |
181 | 181 |
|
182 |
| -- **Example:** |
| 182 | +- **Exemplo:** |
183 | 183 |
|
184 | 184 | ```js
|
185 | 185 | const app = Vue.createApp({
|
|
190 | 190 | c: {
|
191 | 191 | d: 4
|
192 | 192 | },
|
193 |
| - e: 'test', |
| 193 | + e: 'teste', |
194 | 194 | f: 5
|
195 | 195 | }
|
196 | 196 | },
|
197 | 197 | watch: {
|
198 | 198 | a(val, oldVal) {
|
199 | 199 | console.log(`new: ${val}, old: ${oldVal}`)
|
200 | 200 | },
|
201 |
| - // string method name |
| 201 | + // nome do método como string |
202 | 202 | b: 'someMethod',
|
203 |
| - // the callback will be called whenever any of the watched object properties change regardless of their nested depth |
| 203 | + // o callback será chamado na alteração das propriedades do objeto |
| 204 | + // observado, independentemente de sua profundidade aninhada |
204 | 205 | c: {
|
205 | 206 | handler(val, oldVal) {
|
206 |
| - console.log('c changed') |
| 207 | + console.log('c mudou') |
207 | 208 | },
|
208 | 209 | deep: true
|
209 | 210 | },
|
210 |
| - // the callback will be called immediately after the start of the observation |
| 211 | + // o callback será chamado imediatamente após o início da observação |
211 | 212 | e: {
|
212 | 213 | handler(val, oldVal) {
|
213 |
| - console.log('e changed') |
| 214 | + console.log('e mudou') |
214 | 215 | },
|
215 | 216 | immediate: true
|
216 | 217 | },
|
217 |
| - // you can pass array of callbacks, they will be called one-by-one |
| 218 | + // você pode passar um array de callbacks, eles serão chamados um por um |
218 | 219 | f: [
|
219 | 220 | 'handle1',
|
220 | 221 | function handle2(val, oldVal) {
|
221 |
| - console.log('handle2 triggered') |
| 222 | + console.log('handle2 acionado') |
222 | 223 | },
|
223 | 224 | {
|
224 | 225 | handler: function handle3(val, oldVal) {
|
225 |
| - console.log('handle3 triggered') |
| 226 | + console.log('handle3 acionado') |
226 | 227 | }
|
227 | 228 | /* ... */
|
228 | 229 | }
|
229 | 230 | ]
|
230 | 231 | },
|
231 | 232 | methods: {
|
232 | 233 | someMethod() {
|
233 |
| - console.log('b changed') |
| 234 | + console.log('b mudou') |
234 | 235 | },
|
235 | 236 | handle1() {
|
236 |
| - console.log('handle 1 triggered') |
| 237 | + console.log('handle1 acionado') |
237 | 238 | }
|
238 | 239 | }
|
239 | 240 | })
|
|
243 | 244 | vm.a = 3 // => new: 3, old: 1
|
244 | 245 | ```
|
245 | 246 |
|
246 |
| - ::: tip Note |
247 |
| - Note that _you should not use an arrow function to define a watcher_ (e.g. `searchQuery: newValue => this.updateAutocomplete(newValue)`). The reason is arrow functions bind the parent context, so `this` will not be the component instance as you expect and `this.updateAutocomplete` will be undefined. |
| 247 | + ::: tip Nota |
| 248 | + Note que _você não deve usar arrow function para definir um observador_ (ex. `searchQuery: newValue => this.updateAutocomplete(newValue)`). A razão é que *arrow functions* fazem *bind* do contexto pai, então `this` não será a instância do componente como você espera e `this.updateAutocomplete` será `undefined`. |
248 | 249 | :::
|
249 | 250 |
|
250 |
| -- **See also:** [Watchers](../guide/computed.html#watchers) |
| 251 | +- **Ver também:** [Observadores](../guide/computed.html#observadores) |
251 | 252 |
|
252 | 253 | ## emits
|
253 | 254 |
|
254 |
| -- **Type:** `Array<string> | Object` |
| 255 | +- **Tipo:** `Array<string> | Object` |
255 | 256 |
|
256 |
| -- **Details:** |
| 257 | +- **Detalhes:** |
257 | 258 |
|
258 |
| - A list/hash of custom events that can be emitted from the component. It has an Array-based simple syntax and an alternative Object-based syntax that allows to configure an event validation. |
| 259 | + Uma lista/*hash* de eventos personalizados pode ser emitida do componente. Possui tanto uma sintaxe simples baseada em Array como, alternativamente, uma sintaxe baseada em Object que permite configurar uma validação de evento. |
259 | 260 |
|
260 |
| - In Object-based syntax, the value of each property can either be `null` or a validator function. The validation function will receive the additional arguments passed to the `$emit` call. For example, if `this.$emit('foo', 1)` is called, the corresponding validator for `foo` will receive the argument `1`. The validator function should return a boolean to indicate whether the event arguments are valid. |
| 261 | + Na sintaxe baseada em Object, o valor de cada propriedade pode ser `null` ou uma função de validação. A função de validação receberá os argumentos adicionais passados para a chamada `$emit`. Por exemplo, se `this.$emit('foo', 1)` for chamado, o validador correspondente para `foo` receberá o argumento `1`. A função de validação deve retornar um booleano para indicar se os argumentos do evento são válidos. |
261 | 262 |
|
262 |
| -- **Usage:** |
| 263 | +- **Uso:** |
263 | 264 |
|
264 | 265 | ```js
|
265 | 266 | const app = Vue.createApp({})
|
266 | 267 |
|
267 |
| - // Array syntax |
| 268 | + // Sintaxe de Array |
268 | 269 | app.component('todo-item', {
|
269 | 270 | emits: ['check'],
|
270 | 271 | created() {
|
271 | 272 | this.$emit('check')
|
272 | 273 | }
|
273 | 274 | })
|
274 | 275 |
|
275 |
| - // Object syntax |
| 276 | + // Sintaxe de Object |
276 | 277 | app.component('reply-form', {
|
277 | 278 | emits: {
|
278 |
| - // no validation |
| 279 | + // sem validação |
279 | 280 | click: null,
|
280 | 281 |
|
281 |
| - // with validation |
| 282 | + // com validação |
282 | 283 | submit: payload => {
|
283 | 284 | if (payload.email && payload.password) {
|
284 | 285 | return true
|
285 | 286 | } else {
|
286 |
| - console.warn(`Invalid submit event payload!`) |
| 287 | + console.warn(`Payload do evento 'submit' inválido!`) |
287 | 288 | return false
|
288 | 289 | }
|
289 | 290 | }
|
290 | 291 | }
|
291 | 292 | })
|
292 | 293 | ```
|
293 | 294 |
|
294 |
| - ::: tip Note |
295 |
| - Events listed in the `emits` option **will not** be inherited by the root element of the component and also will be excluded from the `$attrs` property. |
| 295 | + ::: tip Nota |
| 296 | + Os eventos listados na opção `emits` **não** serão herdados pelo elemento raiz do componente e também serão excluídos da propriedade `$attrs`. |
296 | 297 | :::
|
297 | 298 |
|
298 |
| -* **See also:** [Attribute Inheritance](../guide/component-attrs.html#attribute-inheritance) |
| 299 | +* **Ver também:** [Herança de Atributos](../guide/component-attrs.html#heranca-de-atributos) |
0 commit comments