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/api/options-composition.md
+66-66Lines changed: 66 additions & 66 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,20 +1,20 @@
1
-
# Composition
1
+
# Composição
2
2
3
-
## mixins
3
+
## `mixins`
4
4
5
-
-**Type:**`Array<Object>`
5
+
-**Tipo:**`Array<Object>`
6
6
7
-
-**Details:**
7
+
-**Detalhes:**
8
8
9
-
The `mixins`option accepts an array of mixin objects. These mixin objects can contain instance options like normal instance objects, and they will be merged against the eventual options using the certain option merging logic. For example, if your mixin contains a `created`hook and the component itself also has one, both functions will be called.
9
+
A opção `mixins`aceita um array de objetos _mixin_. Esses objetos _mixin_ podem conter opções de instância como objetos de instância normais, e eles serão mesclados com as opções eventuais usando a lógica de mesclagem de opções. Por exemplo, se seu _mixin_ contiver um gatilho `created`e o próprio componente também, ambas as funções serão chamadas.
10
10
11
-
Mixin hooks are called in the order they are provided, and called before the component's own hooks.
11
+
Os gatilhos do _mixin_ são chamados na ordem em que são fornecidos e chamados antes dos gatilhos do próprio componente.
12
12
13
13
:::info
14
-
In Vue 2, mixins were the primary mechanism for creating reusable chunks of component logic. While mixins continue to be supported in Vue 3, the [Composition API](/guide/composition-api-introduction.html)is now the preferred approach for code reuse between components.
14
+
No Vue 2, os _mixins_ eram o principal mecanismo para criar blocos reutilizáveis de lógica de componentes. Embora os _mixins_ continuem sendo suportados no Vue 3, a [API de Composição](/guide/composition-api-introduction.html)agora é a abordagem preferida para reutilização de código entre componentes.
15
15
:::
16
16
17
-
-**Example:**
17
+
-**Exemplo:**
18
18
19
19
```js
20
20
constmixin= {
@@ -34,23 +34,23 @@
34
34
// => 2
35
35
```
36
36
37
-
-**See also:**[Mixins](../guide/mixins.html)
37
+
-**Ver também:**[Mixins](../guide/mixins.html)
38
38
39
-
## extends
39
+
## `extends`
40
40
41
-
-**Type:**`Object`
41
+
-**Tipo:**`Object`
42
42
43
-
-**Details:**
43
+
-**Detalhes:**
44
44
45
-
Allows one component to extend another, inheriting its component options.
45
+
Permite que um componente estenda outro, herdando suas opções de componente.
46
46
47
-
From an implementation perspective, `extends`is almost identical to`mixins`. The component specified by`extends`will be treated as though it were the first mixin.
47
+
De uma perspectiva de implementação, `extends`é quase idêntico a`mixins`. O componente especificado por`extends`será tratado como se fosse o primeiro _mixin_.
48
48
49
-
However, `extends`and`mixins`express different intents. The `mixins`option is primarily used to compose chunks of functionality, whereas`extends`is primarily concerned with inheritance.
49
+
No entanto, `extends`e`mixins`expressam intenções diferentes. A opção `mixins`é usada principalmente para compor blocos de funcionalidade, enquanto`extends`está principalmente preocupado com herança.
50
50
51
-
As with `mixins`, any options will be merged using the relevant merge strategy.
51
+
Assim como em `mixins`, todas as opções serão mescladas usando a estratégia de mesclagem relevante.
This pair of options are used together to allow an ancestor component to serve as a dependency injector for all its descendants, regardless of how deep the component hierarchy is, as long as they are in the same parent chain. If you are familiar with React, this is very similar to React's`context`feature.
73
+
Esse par de opções é usado em conjunto para permitir que um componente ancestral sirva como um injetor de dependência para todos os seus descendentes, independentemente da profundidade da hierarquia do componente, desde que estejam na mesma cadeia do pai. Se você estiver familiarizado com React, isso é muito semelhante ao recurso`context`do React.
74
74
75
-
The `provide`option should be an object or a function that returns an object. This object contains the properties that are available for injection into its descendants. You can use ES2015 Symbols as keys in this object, but only in environments that natively support`Symbol`and`Reflect.ownKeys`.
75
+
A opção `provide`deve ser um objeto ou uma função que retorne um objeto. Este objeto contém as propriedades que estão disponíveis para injeção em seus descendentes. Você pode usar Symbols do ES2015 como chaves neste objeto, mas apenas em ambientes que suportem nativamente`Symbol`e`Reflect.ownKeys`.
76
76
77
-
The `inject`option should be either:
77
+
A opção `inject`deve ser:
78
78
79
-
-an array of strings, or
80
-
-an object where the keys are the local binding name and the value is either:
81
-
-the key (string or Symbol) to search for in available injections, or
82
-
-an object where:
83
-
-the `from`property is the key (string or Symbol) to search for in available injections, and
84
-
-the `default`property is used as fallback value
79
+
-um array de strings, ou
80
+
-um objeto em que as chaves são o nome do vínculo local e o valor é:
81
+
-a chave (string ou Symbol) para procurar nas injeções disponíveis, ou
82
+
-um objeto onde:
83
+
-a propriedade `from`é a chave (string ou Symbol) para procurar nas injeções disponíveis, e
84
+
-a propriedade `default`é usada como valor de _fallback_
85
85
86
-
> Note: the `provide`and`inject`bindings are NOT reactive. This is intentional. However, if you pass down a reactive object, properties on that object do remain reactive.
86
+
> Nota: os vínculos `provide`e`inject`NÃO são reativos. Isso é intencional. No entanto, se você transmitir um objeto reativo, as propriedades desse objeto permanecerão reativas.
87
87
88
-
-**Example:**
88
+
-**Exemplo:**
89
89
90
90
```js
91
-
//parent component providing 'foo'
91
+
//componente pai fornecendo 'foo'
92
92
constProvider= {
93
93
provide: {
94
94
foo:'bar'
95
95
}
96
96
// ...
97
97
}
98
98
99
-
//child component injecting 'foo'
99
+
//componente filho injetando 'foo'
100
100
constChild= {
101
101
inject: ['foo'],
102
102
created() {
@@ -106,7 +106,7 @@
106
106
}
107
107
```
108
108
109
-
With ES2015 Symbols, function `provide`and object`inject`:
109
+
Com Symbols do ES2015, a função `provide`e objeto`inject`:
110
110
111
111
```js
112
112
consts=Symbol()
@@ -125,7 +125,7 @@
125
125
}
126
126
```
127
127
128
-
Using an injected value as the default for a prop:
128
+
Usando um valor injetado como _default_ para uma prop:
129
129
130
130
```js
131
131
constChild= {
@@ -140,7 +140,7 @@
140
140
}
141
141
```
142
142
143
-
Using an injected value as data entry:
143
+
Usando um valor injetado como entrada de dados:
144
144
145
145
```js
146
146
constChild= {
@@ -153,7 +153,7 @@
153
153
}
154
154
```
155
155
156
-
Injections can be optional with default value:
156
+
As injeções podem ser opcionais com um valor padrão (_default_):
157
157
158
158
```js
159
159
constChild= {
@@ -163,7 +163,7 @@
163
163
}
164
164
```
165
165
166
-
If it needs to be injected from a property with a different name, use `from`to denote the source property:
166
+
Se precisar ser injetado de uma propriedade com um nome diferente, use `from`para denotar a propriedade de origem:
167
167
168
168
```js
169
169
constChild= {
@@ -176,7 +176,7 @@
176
176
}
177
177
```
178
178
179
-
Similar to prop defaults, you need to use a factory function for non-primitive values:
179
+
Semelhante aos valores padrão de prop, você precisa usar uma função fabricadora para valores não primitivos:
The `setup`function is a new component option. It serves as the entry point for using the Composition API inside components.
198
+
A função `setup`é uma nova opção de componente. Ela serve como ponto de entrada para usar a API de Composição dentro dos componentes.
199
199
200
-
-**Invocation Timing**
200
+
-**Momento de Invocação**
201
201
202
-
`setup`is called right after the initial props resolution when a component instance is created. Lifecycle-wise, it is called before the [beforeCreate](./options-lifecycle-hooks.html#beforecreate) hook.
202
+
`setup`é chamada logo após a resolução inicial das props quando uma instância do componente é criada. Em termos de ciclo de vida, ela é chamado antes do gatilho [beforeCreate](./options-lifecycle-hooks.html#beforecreate).
203
203
204
-
-**Usage with Templates**
204
+
-**Uso com _templates_**
205
205
206
-
If`setup`returns an object, the properties on the object will be merged on to the render context for the component's template:
206
+
Se`setup`retornar um objeto, as propriedades do objeto serão mescladas no contexto de renderização do _template_ do componente:
207
207
208
208
```html
209
209
<template>
@@ -218,7 +218,7 @@ The `setup` function is a new component option. It serves as the entry point for
218
218
constcount=ref(0)
219
219
constobject=reactive({ foo:'bar' })
220
220
221
-
//expose to template
221
+
//expõe ao template
222
222
return {
223
223
count,
224
224
object
@@ -228,11 +228,11 @@ The `setup` function is a new component option. It serves as the entry point for
228
228
</script>
229
229
```
230
230
231
-
Note that[refs](refs-api.html#ref)returned from`setup`are automatically unwrapped when accessed in the template so there's no need for `.value`in templates.
231
+
Note que[refs](refs-api.html#ref)retornados de`setup`são automaticamente desempacotadas quando acessados no _template_, então não há necessidade de `.value`nos _templates_.
232
232
233
-
-**Usage with Render Functions / JSX**
233
+
-**Uso com Funções de Renderização / JSX**
234
234
235
-
`setup`can also return a render function, which can directly make use of reactive state declared in the same scope:
235
+
`setup`também pode retornar uma função de renderização, que pode usar diretamente o estado reativo declarado no mesmo escopo:
236
236
237
237
```js
238
238
import { h, ref, reactive } from'vue'
@@ -247,9 +247,9 @@ The `setup` function is a new component option. It serves as the entry point for
247
247
}
248
248
```
249
249
250
-
-**Arguments**
250
+
-**Argumentos**
251
251
252
-
The function receives the resolved props as its first argument:
252
+
A função recebe as props resolvidas como seu primeiro argumento:
253
253
254
254
```js
255
255
exportdefault {
@@ -262,7 +262,7 @@ The `setup` function is a new component option. It serves as the entry point for
262
262
}
263
263
```
264
264
265
-
Note this `props`object is reactive - i.e. it is updated when new props are passed in, and can be observed and reacted upon using `watchEffect`or`watch`:
265
+
Observe que este objeto `props`é reativo - ou seja, ele é atualizado quando novas props são passadas e pode ser observado e reagido ao usar `watchEffect`ou`watch`:
266
266
267
267
```js
268
268
exportdefault {
@@ -271,13 +271,13 @@ The `setup` function is a new component option. It serves as the entry point for
271
271
},
272
272
setup(props) {
273
273
watchEffect(() => {
274
-
console.log(`name is: `+props.name)
274
+
console.log(`nome é: `+props.name)
275
275
})
276
276
}
277
277
}
278
278
```
279
279
280
-
However, do NOT destructure the`props` object, as it will lose reactivity:
280
+
No entanto, NÃO desestruture o objeto`props`, pois ele perderá reatividade:
281
281
282
282
```js
283
283
exportdefault {
@@ -286,15 +286,15 @@ The `setup` function is a new component option. It serves as the entry point for
286
286
},
287
287
setup({ name }) {
288
288
watchEffect(() => {
289
-
console.log(`name is: `+ name) //Will not be reactive!
289
+
console.log(`nome é: `+ name) //Não será reativo!
290
290
})
291
291
}
292
292
}
293
293
```
294
294
295
-
The `props`object is immutable for userland code during development (will emit warning if user code attempts to mutate it).
295
+
O objeto `props`é imutável para o código do usuário durante o desenvolvimento (irá emitir um aviso se o código do usuário tentar alterá-lo).
296
296
297
-
The second argument provides a context object which exposes a selective list of properties that were previously exposed on`this`:
297
+
O segundo argumento fornece um objeto de contexto que expõe uma lista seletiva de propriedades que foram expostas anteriormente em`this`:
298
298
299
299
```js
300
300
constMyComponent= {
@@ -306,23 +306,23 @@ The `setup` function is a new component option. It serves as the entry point for
306
306
}
307
307
```
308
308
309
-
`attrs`and`slots`are proxies to the corresponding values on the internal component instance. This ensures they always expose the latest values even after updates so that we can destructure them without worrying about accessing a stale reference:
309
+
`attrs`e`slots`são _proxies_ para os valores correspondentes na instância interna do componente. Isso garante que eles sempre exponham os valores mais recentes, mesmo após as atualizações, para que possamos desestruturá-los sem nos preocupar em acessar uma referência obsoleta:
310
310
311
311
```js
312
312
constMyComponent= {
313
313
setup(props, { attrs }) {
314
-
//a function that may get called at a later stage
314
+
//uma função que pode ser chamada em um estágio posterior
315
315
functiononClick() {
316
-
console.log(attrs.foo) //guaranteed to be the latest reference
316
+
console.log(attrs.foo) //garantido ser a referência mais recente
317
317
}
318
318
}
319
319
}
320
320
```
321
321
322
-
There are a number of reasons for placing `props`as a separate first argument instead of including it in the context:
322
+
Existem várias razões para colocar `props`como um primeiro argumento separado em vez de incluí-lo no contexto:
323
323
324
-
-It's much more common for a component to use `props`than the other properties, and very often a component uses only`props`.
324
+
-É muito mais comum um componente usar `props`do que as outras propriedades, e muitas vezes um componente usa apenas`props`.
325
325
326
-
-Having`props`as a separate argument makes it easier to type it individually without messing up the types of other properties on the context. It also makes it possible to keep a consistent signature across `setup`, `render`and plain functional components with TSX support.
326
+
-Ter`props`como um argumento separado torna mais fácil digitá-lo individualmente sem atrapalhar os tipos de outras propriedades no contexto. Também torna possível manter uma assinatura consistente em `setup`, `render`e componentes funcionais simples com suporte a TSX.
0 commit comments