Skip to content

Commit bba924a

Browse files
author
Paulo Henrique da Fonseca Bueno
committed
translation of the mixins.md file was carried out to resolve issue 120
1 parent 309df27 commit bba924a

File tree

1 file changed

+55
-53
lines changed

1 file changed

+55
-53
lines changed

src/guide/mixins.md

Lines changed: 55 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,43 @@
11
# Mixins
22

3-
## Basics
3+
## Fundamentos
44

5-
Mixins distribute reusable functionalities for Vue components. A mixin object can contain any component options. When a component uses a mixin, all options in the mixin will be "mixed" into the component's own options.
5+
Mixins distribuem funcionalidades reutilizáveis ​​para componentes Vue. Um objeto mixin pode conter qualquer opção de componente. Quando um componente usa um mixin, todas as opções do mixin serão "combinadas" com as opções do próprio componente.
66

7-
Example:
7+
Exemplo:
88

99
```js
10-
// define a mixin object
10+
// define um objeto mixin
1111
const myMixin = {
1212
created() {
1313
this.hello()
1414
},
1515
methods: {
1616
hello() {
17-
console.log('hello from mixin!')
17+
console.log('olá do mixin!')
1818
}
1919
}
2020
}
2121

22-
// define an app that uses this mixin
22+
// definir um aplicativo que usa este mixin
2323
const app = Vue.createApp({
2424
mixins: [myMixin]
2525
})
2626

27-
app.mount('#mixins-basic') // => "hello from mixin!"
27+
app.mount('#mixins-basic') // => "olá do mixin!"
2828
```
2929

30-
## Option Merging
30+
## Opção de mesclagem
3131

32-
When a mixin and the component itself contain overlapping options, they will be "merged" using appropriate strategies.
32+
Quando um mixin e o próprio componente contêm opções de sobreposição, eles serão "mesclados" usando estratégias apropriadas.
3333

34-
For example, data objects undergo a recursive merge, with the component's data taking priority in cases of conflicts.
34+
Por exemplo, objetos de dados passam por uma mesclagem recursiva, com os dados do componente tendo prioridade em casos de conflito.
3535

3636
```js
3737
const myMixin = {
3838
data() {
3939
return {
40-
message: 'hello',
40+
message: 'olá',
4141
foo: 'abc'
4242
}
4343
}
@@ -47,37 +47,37 @@ const app = Vue.createApp({
4747
mixins: [myMixin],
4848
data() {
4949
return {
50-
message: 'goodbye',
50+
message: 'Tchau',
5151
bar: 'def'
5252
}
5353
},
5454
created() {
55-
console.log(this.$data) // => { message: "goodbye", foo: "abc", bar: "def" }
55+
console.log(this.$data) // => { message: "Tchau", foo: "abc", bar: "def" }
5656
}
5757
})
5858
```
5959

60-
Hook functions with the same name are merged into an array so that all of them will be called. Mixin hooks will be called **before** the component's own hooks.
60+
Funções hoocks com o mesmo nome são mescladas em um array para que todas sejam chamadas. Os hoocks do Mixin serão chamados **antes** dos próprios hoocks do componente.
6161

6262
```js
6363
const myMixin = {
6464
created() {
65-
console.log('mixin hook called')
65+
console.log('hook do mixin chamando')
6666
}
6767
}
6868

6969
const app = Vue.createApp({
7070
mixins: [myMixin],
7171
created() {
72-
console.log('component hook called')
72+
console.log('hook do componente chamando')
7373
}
7474
})
7575

76-
// => "mixin hook called"
77-
// => "component hook called"
76+
// => "hook do mixin chamando"
77+
// => "hook do componente chamando"
7878
```
7979

80-
Options that expect object values, for example `methods`, `components` and `directives`, will be merged into the same object. The component's options will take priority when there are conflicting keys in these objects:
80+
Opções que esperam valores de objeto, por exemplo `methods`, `components` e `directives`, será mesclado no mesmo objeto. As opções do componente terão prioridade quando houver chaves conflitantes nestes objetos:
8181

8282
```js
8383
const myMixin = {
@@ -86,7 +86,7 @@ const myMixin = {
8686
console.log('foo')
8787
},
8888
conflicting() {
89-
console.log('from mixin')
89+
console.log('do mixin')
9090
}
9191
}
9292
}
@@ -98,7 +98,7 @@ const app = Vue.createApp({
9898
console.log('bar')
9999
},
100100
conflicting() {
101-
console.log('from self')
101+
console.log('de si mesmo')
102102
}
103103
}
104104
})
@@ -107,19 +107,19 @@ const vm = app.mount('#mixins-basic')
107107

108108
vm.foo() // => "foo"
109109
vm.bar() // => "bar"
110-
vm.conflicting() // => "from self"
110+
vm.conflicting() // => "de si mesmo"
111111
```
112112

113-
## Global Mixin
113+
## Mixin Global
114114

115-
You can also apply a mixin globally for a Vue application:
115+
Você também pode aplicar um mixin globalmente para um aplicativo Vue:
116116

117117
```js
118118
const app = Vue.createApp({
119-
myOption: 'hello!'
119+
myOption: 'Olá!'
120120
})
121121

122-
// inject a handler for `myOption` custom option
122+
// injetar um handler para `myOption` opção personalizada
123123
app.mixin({
124124
created() {
125125
const myOption = this.$options.myOption
@@ -129,17 +129,17 @@ app.mixin({
129129
}
130130
})
131131

132-
app.mount('#mixins-global') // => "hello!"
132+
app.mount('#mixins-global') // => "Olá!"
133133
```
134134

135-
Use with caution! Once you apply a mixin globally, it will affect **every** component instance created afterwards in the given app (for example, child components):
135+
Use com cuidado! Depois de aplicar um mixin globalmente, ele afetará **cada** instância de componente criada posteriormente no aplicativo fornecido (por exemplo, componentes filhos):
136136

137137
```js
138138
const app = Vue.createApp({
139-
myOption: 'hello!'
139+
myOption: 'Olá!'
140140
})
141141

142-
// inject a handler for `myOption` custom option
142+
// injetar um handler para `myOption` opção personalizada
143143
app.mixin({
144144
created() {
145145
const myOption = this.$options.myOption
@@ -149,76 +149,78 @@ app.mixin({
149149
}
150150
})
151151

152-
// add myOption also to child component
152+
// adicione myOption também ao componente filho
153153
app.component('test-component', {
154-
myOption: 'hello from component!'
154+
myOption: 'Olá do componente!'
155155
})
156156

157157
app.mount('#mixins-global')
158158

159-
// => "hello!"
160-
// => "hello from component!"
159+
// => "Olá!"
160+
// => "Olá do componente"
161161
```
162162

163-
In most cases, you should only use it for custom option handling like demonstrated in the example above. It's also a good idea to ship them as [Plugins](plugins.html) to avoid duplicate application.
163+
Na maioria dos casos, você só deve usá-lo para manipulação de opções personalizadas, conforme demonstrado no exemplo acima. Também é uma boa ideia enviá-los como [Plugins](plugins.html) para evitar a aplicação duplicada.
164164

165-
## Custom Option Merge Strategies
165+
## Estratégias de combinação de opções personalizadas
166166

167-
When custom options are merged, they use the default strategy which overwrites the existing value. If you want a custom option to be merged using custom logic, you need to attach a function to `app.config.optionMergeStrategies`:
167+
Quando as opções personalizadas são mescladas, elas usam a estratégia padrão que substitui o valor existente. Se você deseja que uma opção personalizada seja mesclada usando uma lógica personalizada, você precisa anexar uma função `app.config.optionMergeStrategies`:
168168

169169
```js
170170
const app = Vue.createApp({})
171171

172172
app.config.optionMergeStrategies.customOption = (toVal, fromVal) => {
173-
// return mergedVal
173+
// retorna mergedVal
174174
}
175175
```
176176

177-
The merge strategy receives the value of that option defined on the parent and child instances as the first and second arguments, respectively. Let's try to check what do we have in these parameters when we use a mixin:
177+
A estratégia de mesclagem recebe o valor dessa opção definida nas instâncias pai e filho como o primeiro e segundo argumentos, respectivamente. Vamos tentar verificar o que temos nesses parâmetros quando usamos um mixin:
178178

179179
```js
180180
const app = Vue.createApp({
181-
custom: 'hello!'
181+
custom: 'Olá!'
182182
})
183183

184184
app.config.optionMergeStrategies.custom = (toVal, fromVal) => {
185185
console.log(fromVal, toVal)
186-
// => "goodbye!", undefined
187-
// => "hello", "goodbye!"
186+
// => "Tchau!", undefined
187+
// => "Olá", "Tchau!"
188188
return fromVal || toVal
189189
}
190190

191191
app.mixin({
192-
custom: 'goodbye!',
192+
custom: 'Tchau!',
193193
created() {
194-
console.log(this.$options.custom) // => "hello!"
194+
console.log(this.$options.custom) // => "Olá!"
195195
}
196196
})
197197
```
198198

199-
As you can see, in the console we have `toVal` and `fromVal` printed first from the mixin and then from the `app`. We always return `fromVal` if it exists, that's why `this.$options.custom` is set to `hello!` in the end. Let's try to change a strategy to _always return a value from the child instance_:
199+
Como você pode ver, no console temos `toVal` e `fromVal` impresso primeiro no mixin e depois no `app`.
200+
Nós sempre voltamos `fromVal` se existe é por isso `this.$options.custom` está configurado para `hello!`
201+
No final. Vamos tentar mudar uma estratégia para sempre retornar um valor da instância filha:
200202

201203
```js
202204
const app = Vue.createApp({
203-
custom: 'hello!'
205+
custom: 'Olá!'
204206
})
205207

206208
app.config.optionMergeStrategies.custom = (toVal, fromVal) => toVal || fromVal
207209

208210
app.mixin({
209-
custom: 'goodbye!',
211+
custom: 'Tchau!',
210212
created() {
211-
console.log(this.$options.custom) // => "goodbye!"
213+
console.log(this.$options.custom) // => "Tchau!"
212214
}
213215
})
214216
```
215217

216-
## Precautions
218+
## Precauções
217219

218-
In Vue 2, mixins were the primary tool to abstract parts of component logic into reusable chunks. However, they have a few issues:
220+
No Vue 2, os mixins eram a principal ferramenta para abstrair partes da lógica de componentes em blocos reutilizáveis. No entanto, eles têm alguns problemas:
219221

220-
- Mixins are conflict-prone: Since properties from each feature are merged into the same component, you still have to know about every other feature to avoid property name conflicts and for debugging.
222+
- Mixins são propensos a conflitos: como as propriedades de cada recurso são mescladas no mesmo componente, você ainda precisa conhecer todos os outros recursos para evitar conflitos de nome de propriedade e para depuração.
221223

222-
- Reusability is limited: we cannot pass any parameters to the mixin to change its logic which reduces their flexibility in terms of abstracting logic
224+
- Reutilização é limitada: não podemos passar nenhum parâmetro ao mixin para alterar sua lógica, o que reduz sua flexibilidade em termos de abstração da lógica
223225

224-
To address these issues, we added a new way to organize code by logical concerns: the [Composition API](composition-api-introduction.html).
226+
Para resolver esses problemas, adicionamos uma nova maneira de organizar o código por questões lógicas: [API de composição](composition-api-introduction.html).

0 commit comments

Comments
 (0)