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
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.
6
6
7
-
Example:
7
+
Exemplo:
8
8
9
9
```js
10
-
// define a mixin object
10
+
// define um objeto mixin
11
11
constmyMixin= {
12
12
created() {
13
13
this.hello()
14
14
},
15
15
methods: {
16
16
hello() {
17
-
console.log('hello from mixin!')
17
+
console.log('olá do mixin!')
18
18
}
19
19
}
20
20
}
21
21
22
-
//define an app that uses this mixin
22
+
//definir um aplicativo que usa este mixin
23
23
constapp=Vue.createApp({
24
24
mixins: [myMixin]
25
25
})
26
26
27
-
app.mount('#mixins-basic') // => "hello from mixin!"
27
+
app.mount('#mixins-basic') // => "olá do mixin!"
28
28
```
29
29
30
-
## Option Merging
30
+
## Opção de mesclagem
31
31
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.
33
33
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.
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.
61
61
62
62
```js
63
63
constmyMixin= {
64
64
created() {
65
-
console.log('mixin hook called')
65
+
console.log('hook do mixin chamando')
66
66
}
67
67
}
68
68
69
69
constapp=Vue.createApp({
70
70
mixins: [myMixin],
71
71
created() {
72
-
console.log('component hook called')
72
+
console.log('hook do componente chamando')
73
73
}
74
74
})
75
75
76
-
// => "mixin hook called"
77
-
// => "component hook called"
76
+
// => "hook do mixin chamando"
77
+
// => "hook do componente chamando"
78
78
```
79
79
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:
81
81
82
82
```js
83
83
constmyMixin= {
@@ -86,7 +86,7 @@ const myMixin = {
86
86
console.log('foo')
87
87
},
88
88
conflicting() {
89
-
console.log('from mixin')
89
+
console.log('do mixin')
90
90
}
91
91
}
92
92
}
@@ -98,7 +98,7 @@ const app = Vue.createApp({
98
98
console.log('bar')
99
99
},
100
100
conflicting() {
101
-
console.log('from self')
101
+
console.log('de si mesmo')
102
102
}
103
103
}
104
104
})
@@ -107,19 +107,19 @@ const vm = app.mount('#mixins-basic')
107
107
108
108
vm.foo() // => "foo"
109
109
vm.bar() // => "bar"
110
-
vm.conflicting() // => "from self"
110
+
vm.conflicting() // => "de si mesmo"
111
111
```
112
112
113
-
## Global Mixin
113
+
## Mixin Global
114
114
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:
116
116
117
117
```js
118
118
constapp=Vue.createApp({
119
-
myOption:'hello!'
119
+
myOption:'Olá!'
120
120
})
121
121
122
-
//inject a handler for `myOption` custom option
122
+
//injetar um handler para `myOption` opção personalizada
123
123
app.mixin({
124
124
created() {
125
125
constmyOption=this.$options.myOption
@@ -129,17 +129,17 @@ app.mixin({
129
129
}
130
130
})
131
131
132
-
app.mount('#mixins-global') // => "hello!"
132
+
app.mount('#mixins-global') // => "Olá!"
133
133
```
134
134
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):
136
136
137
137
```js
138
138
constapp=Vue.createApp({
139
-
myOption:'hello!'
139
+
myOption:'Olá!'
140
140
})
141
141
142
-
//inject a handler for `myOption` custom option
142
+
//injetar um handler para `myOption` opção personalizada
143
143
app.mixin({
144
144
created() {
145
145
constmyOption=this.$options.myOption
@@ -149,76 +149,78 @@ app.mixin({
149
149
}
150
150
})
151
151
152
-
//add myOption also to child component
152
+
//adicione myOption também ao componente filho
153
153
app.component('test-component', {
154
-
myOption:'hello from component!'
154
+
myOption:'Olá do componente!'
155
155
})
156
156
157
157
app.mount('#mixins-global')
158
158
159
-
// => "hello!"
160
-
// => "hello from component!"
159
+
// => "Olá!"
160
+
// => "Olá do componente"
161
161
```
162
162
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.
164
164
165
-
## Custom Option Merge Strategies
165
+
## Estratégias de combinação de opções personalizadas
166
166
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`:
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:
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:
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:
219
221
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.
221
223
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
223
225
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