Skip to content

Commit 73c8736

Browse files
committed
Translation of api/options-composition
1 parent e7932a3 commit 73c8736

File tree

1 file changed

+66
-66
lines changed

1 file changed

+66
-66
lines changed

src/api/options-composition.md

Lines changed: 66 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,20 @@
1-
# Composition
1+
# Composição
22

3-
## mixins
3+
## `mixins`
44

5-
- **Type:** `Array<Object>`
5+
- **Tipo:** `Array<Object>`
66

7-
- **Details:**
7+
- **Detalhes:**
88

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

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

1313
:::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.
1515
:::
1616

17-
- **Example:**
17+
- **Exemplo:**
1818

1919
```js
2020
const mixin = {
@@ -34,23 +34,23 @@
3434
// => 2
3535
```
3636

37-
- **See also:** [Mixins](../guide/mixins.html)
37+
- **Ver também:** [Mixins](../guide/mixins.html)
3838

39-
## extends
39+
## `extends`
4040

41-
- **Type:** `Object`
41+
- **Tipo:** `Object`
4242

43-
- **Details:**
43+
- **Detalhes:**
4444

45-
Allows one component to extend another, inheriting its component options.
45+
Permite que um componente estenda outro, herdando suas opções de componente.
4646

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_.
4848

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

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

53-
- **Example:**
53+
- **Exemplo:**
5454

5555
```js
5656
const CompA = { ... }
@@ -61,42 +61,42 @@
6161
}
6262
```
6363

64-
## provide / inject
64+
## `provide` / `inject`
6565

66-
- **Type:**
66+
- **Tipo:**
6767

6868
- **provide:** `Object | () => Object`
6969
- **inject:** `Array<string> | { [key: string]: string | Symbol | Object }`
7070

71-
- **Details:**
71+
- **Detalhes:**
7272

73-
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.
7474

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`.
7676

77-
The `inject` option should be either:
77+
A opção `inject` deve ser:
7878

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_
8585

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.
8787
88-
- **Example:**
88+
- **Exemplo:**
8989

9090
```js
91-
// parent component providing 'foo'
91+
// componente pai fornecendo 'foo'
9292
const Provider = {
9393
provide: {
9494
foo: 'bar'
9595
}
9696
// ...
9797
}
9898

99-
// child component injecting 'foo'
99+
// componente filho injetando 'foo'
100100
const Child = {
101101
inject: ['foo'],
102102
created() {
@@ -106,7 +106,7 @@
106106
}
107107
```
108108

109-
With ES2015 Symbols, function `provide` and object `inject`:
109+
Com Symbols do ES2015, a função `provide` e objeto `inject`:
110110

111111
```js
112112
const s = Symbol()
@@ -125,7 +125,7 @@
125125
}
126126
```
127127

128-
Using an injected value as the default for a prop:
128+
Usando um valor injetado como _default_ para uma prop:
129129

130130
```js
131131
const Child = {
@@ -140,7 +140,7 @@
140140
}
141141
```
142142

143-
Using an injected value as data entry:
143+
Usando um valor injetado como entrada de dados:
144144

145145
```js
146146
const Child = {
@@ -153,7 +153,7 @@
153153
}
154154
```
155155

156-
Injections can be optional with default value:
156+
As injeções podem ser opcionais com um valor padrão (_default_):
157157

158158
```js
159159
const Child = {
@@ -163,7 +163,7 @@
163163
}
164164
```
165165

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

168168
```js
169169
const Child = {
@@ -176,7 +176,7 @@
176176
}
177177
```
178178

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

181181
```js
182182
const Child = {
@@ -189,21 +189,21 @@
189189
}
190190
```
191191

192-
- **See also:** [Provide / Inject](../guide/component-provide-inject.html)
192+
- **Ver também:** [Prover / Injetar](../guide/component-provide-inject.html)
193193

194-
## setup
194+
## `setup`
195195

196-
- **Type:** `Function`
196+
- **Tipo:** `Function`
197197

198-
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.
199199

200-
- **Invocation Timing**
200+
- **Momento de Invocação**
201201

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).
203203

204-
- **Usage with Templates**
204+
- **Uso com _templates_**
205205

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

208208
```html
209209
<template>
@@ -218,7 +218,7 @@ The `setup` function is a new component option. It serves as the entry point for
218218
const count = ref(0)
219219
const object = reactive({ foo: 'bar' })
220220
221-
// expose to template
221+
// expõe ao template
222222
return {
223223
count,
224224
object
@@ -228,11 +228,11 @@ The `setup` function is a new component option. It serves as the entry point for
228228
</script>
229229
```
230230

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_.
232232

233-
- **Usage with Render Functions / JSX**
233+
- **Uso com Funções de Renderização / JSX**
234234

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

237237
```js
238238
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
247247
}
248248
```
249249

250-
- **Arguments**
250+
- **Argumentos**
251251

252-
The function receives the resolved props as its first argument:
252+
A função recebe as props resolvidas como seu primeiro argumento:
253253

254254
```js
255255
export default {
@@ -262,7 +262,7 @@ The `setup` function is a new component option. It serves as the entry point for
262262
}
263263
```
264264

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

267267
```js
268268
export default {
@@ -271,13 +271,13 @@ The `setup` function is a new component option. It serves as the entry point for
271271
},
272272
setup(props) {
273273
watchEffect(() => {
274-
console.log(`name is: ` + props.name)
274+
console.log(`nome é: ` + props.name)
275275
})
276276
}
277277
}
278278
```
279279

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

282282
```js
283283
export default {
@@ -286,15 +286,15 @@ The `setup` function is a new component option. It serves as the entry point for
286286
},
287287
setup({ name }) {
288288
watchEffect(() => {
289-
console.log(`name is: ` + name) // Will not be reactive!
289+
console.log(`nome é: ` + name) // Não será reativo!
290290
})
291291
}
292292
}
293293
```
294294

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).
296296

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

299299
```js
300300
const MyComponent = {
@@ -306,23 +306,23 @@ The `setup` function is a new component option. It serves as the entry point for
306306
}
307307
```
308308

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

311311
```js
312312
const MyComponent = {
313313
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
315315
function onClick() {
316-
console.log(attrs.foo) // guaranteed to be the latest reference
316+
console.log(attrs.foo) // garantido ser a referência mais recente
317317
}
318318
}
319319
}
320320
```
321321

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

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`.
325325

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

328-
- **See also:** [Composition API](composition-api.html)
328+
- **Ver também:** [API de Composição](composition-api.html)

0 commit comments

Comments
 (0)