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/guide/component-custom-events.md
+37-37Lines changed: 37 additions & 37 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,62 +1,62 @@
1
-
# Custom Events
1
+
# Eventos Customizados
2
2
3
-
> This page assumes you've already read the [Components Basics](component-basics.md). Read that first if you are new to components.
3
+
> Esta página assume que você já leu o [Básico sobre Componentes](component-basics.md). Leia lá antes se você está iniciando com componentes.
4
4
5
-
## Event Names
5
+
## Nomes de Eventos
6
6
7
-
Unlike components and props, event names don't provide any automatic case transformation. Instead, the name of an emitted event must exactly match the name used to listen to that event. For example, if emitting a camelCased event name:
7
+
Diferente de componentes e propriedades, os nomes de eventos não convertem automaticamente maiúsculas e minúsculas. Em vez disso, o nome de um evento emitido deve corresponder exatamente ao nome usado para escutar este evento. Por exemplo, se emitir um evento com nome em camelCase:
8
8
9
9
```js
10
10
this.$emit('myEvent')
11
11
```
12
12
13
-
Listening to the kebab-cased version will have no effect:
Since event names will never be used as variable or property names in JavaScript, there is no reason to use camelCase or PascalCase. Additionally, `v-on`event listeners inside DOM templates will be automatically transformed to lowercase (due to HTML's case-insensitivity), so`@myEvent`would become`@myevent` -- making`myEvent`impossible to listen to.
20
+
Considerando que os nomes de eventos nunca serão usados como nomes de variáveis ou de propriedades no JavaScript, não há razão para usar camelCase ou PascalCase. Além disso, escutadores de eventos `v-on`dentro dos templates DOM serão automaticamente transformados em minúsculas (devido ao HTML ser insensível à maiúsculas e minúsculas), então`@myEvent`se tornará`@myevent` -- fazendo`myEvent`impossível de ser escutado.
21
21
22
-
For these reasons, we recommend you **always use kebab-case for event names**.
22
+
Por estas razões, nós recomendamos que você **sempre use kebab-case para nomes de eventos**.
23
23
24
-
## Defining Custom Events
24
+
## Definindo Eventos Customizados
25
25
26
-
<VideoLessonhref="https://vueschool.io/lessons/defining-custom-events-emits?friend=vuejs"title="Learn how to define which events a component can emit with Vue School">Watch a free video about Defining Custom Events on Vue School</VideoLesson>
26
+
<VideoLessonhref="https://vueschool.io/lessons/defining-custom-events-emits?friend=vuejs"title="Aprenda à definir quais eventos um componente pode emitir com a Vue School (em inglês)">Assista um vídeo grátis sobre como definir Eventos Customizados na Vue School (em inglês)</VideoLesson>
27
27
28
-
Emitted events can be defined on the component via the `emits` option.
28
+
Os eventos emitidos podem ser definidos no componente através da opção `emits`.
29
29
30
30
```js
31
31
app.component('custom-form', {
32
32
emits: ['in-focus', 'submit']
33
33
})
34
34
```
35
35
36
-
When a native event (e.g., `click`) is defined in the`emits` option, the component event will be used __instead__ of a native event listener.
36
+
Quando um evento nativo (por exemplo, `click`) for definido na opção`emits`, o evento do componente será usado __ao invés__ de um escutador de evento nativo.
37
37
38
-
::: tip
39
-
It is recommended to define all emitted events in order to better document how a component should work.
38
+
::: tip DICA
39
+
Recomenda-se definir todos os eventos emitidos para documentar melhor como o componente deve funcionar.
40
40
:::
41
41
42
-
### Validate Emitted Events
42
+
### Validar Eventos Emitidos
43
43
44
-
Similar to prop type validation, an emitted event can be validated if it is defined with the Object syntax instead of the Array syntax.
44
+
Semelhante à validação de propriedades, um evento emitido pode ser validado se for definido com a sintaxe Object em vez da sintaxe Array.
45
45
46
-
To add validation, the event is assigned a function that receives the arguments passed to the`$emit`call and returns a boolean to indicate whether the event is valid or not.
46
+
Para adicionar validação, o evento recebe uma função que recebe os argumentos passados para a chamada`$emit`e retorna um booleano para indicar se o evento é válido ou não.
47
47
48
48
```js
49
49
app.component('custom-form', {
50
50
emits: {
51
-
//No validation
51
+
//Sem validação
52
52
click:null,
53
53
54
-
//Validate submit event
54
+
//Validar evento submit
55
55
submit: ({ email, password }) => {
56
56
if (email && password) {
57
57
returntrue
58
58
} else {
59
-
console.warn('Invalid submit event payload!')
59
+
console.warn('Argumentos inválidos para o evento submit!')
By default, `v-model`on a component uses `modelValue`as the prop and `update:modelValue`as the event. We can modify these names passing an argument to`v-model`:
74
+
Por padrão, em um componente o `v-model`usa `modelValue`como propriedade e `update:modelValue`como evento. Podemos modificar esses nomes passando um argumento para`v-model`:
By leveraging the ability to target a particular prop and event as we learned before with [`v-model` arguments](#v-model-arguments), we can now create multiple v-model bindings on a single component instance.
104
+
Aproveitando a capacidade de direcionar uma determinada propriedade e evento como aprendemos antes em [argumentos do `v-model`](#argumentos-do-v-model), agora podemos criar múltiplos vínculos de `v-model` em uma única instância do componente.
105
105
106
-
Each v-model will sync to a different prop, without the need for extra options in the component:
106
+
Cada `v-model` será sincronizado com uma propriedade diferente, sem a necessidade de opções extras no componente:
When we were learning about form input bindings, we saw that `v-model`has [built-in modifiers](/guide/forms.html#modifiers) - `.trim`, `.number`and`.lazy`. In some cases, however, you might also want to add your own custom modifiers.
146
+
Quando estávamos aprendendo sobre interligações em elementos _input_, vimos que `v-model`tem [modificadores embutidos](/guide/forms.html#modifiers) - `.trim`, `.number`e`.lazy`. Em alguns casos, entretanto, você também pode querer adicionar seus próprios modificadores personalizados.
147
147
148
-
Let's create an example custom modifier, `capitalize`, that capitalizes the first letter of the string provided by the`v-model` binding.
148
+
Vamos criar um modificador personalizado de exemplo, `capitalize`, que coloca em maiúscula a primeira letra da string fornecida pela vinculação`v-model`.
149
149
150
-
Modifiers added to a component `v-model`will be provided to the component via the `modelModifiers` prop. In the below example, we have created a component that contains a `modelModifiers`prop that defaults to an empty object.
150
+
Modificadores adicionados ao `v-model`de um componente serão fornecidos ao componente por meio da propriedade `modelModifiers`. No exemplo abaixo, criamos um componente que contém uma propriedade `modelModifiers`cujo padrão é um objeto vazio.
151
151
152
-
Notice that when the component's `created`lifecycle hook triggers, the `modelModifiers`prop contains `capitalize`and its value is`true` - due to it being set on the `v-model` binding`v-model.capitalize="bar"`.
152
+
Observe que quando o gatilho do ciclo de vida `created`do componente é acionado, a propriedade `modelModifiers`contém `capitalize`e seu valor é`true` - devido ao fato de ser definido na vinculação`v-model.capitalize="bar"`.
Now that we have our prop set up, we can check the`modelModifiers`object keys and write a handler to change the emitted value. In the code below we will capitalize the string whenever the`<input />`element fires an`input` event.
177
+
Agora que temos nossa propriedade configurada, podemos verificar as chaves do objeto`modelModifiers`e escrever um manipulador para alterar o valor emitido. No código a seguir, colocaremos a string em maiúscula sempre que o elemento`<input />`disparar um evento`input`.
0 commit comments