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
We can use the`v-on` directive, which we typically shorten to the`@` symbol, to listen to DOM events and run some JavaScript when they're triggered. The usage would be `v-on:click="methodName"`or with the shortcut, `@click="methodName"`
5
+
Podemos usar a diretiva`v-on`, que normalmente abreviamos para o símbolo`@`, para escutar eventos do DOM e rodar algum JavaScript quando tal evento for disparado. A maneira de usar seria `v-on:click="methodName"`ou com o atalho, `@click="methodName"`
6
6
7
-
For example:
7
+
Por exemplo:
8
8
9
9
```html
10
10
<divid="basic-event">
11
-
<button@click="counter += 1">Add 1</button>
12
-
<p>The button above has been clicked {{ counter}} times.</p>
11
+
<button@click="counter += 1">Adicionar 1</button>
12
+
<p>O botão acima foi clicado {{counter}} vezes.</p>
The logic for many event handlers will be more complex though, so keeping your JavaScript in the value of the `v-on`attribute isn't feasible. That's why `v-on`can also accept the name of a method you'd like to call.
37
+
A lógica para muitos manipuladores de evento será mais complexa, portanto, manter diretamente código JavaScript no valor do atributo `v-on`não é viável. É por isso que `v-on`também pode aceitar o nome de um método que você gostaria de chamar.
38
38
39
-
For example:
39
+
Por Exemplo:
40
40
41
41
```html
42
42
<divid="event-with-method">
43
-
<!-- `greet` is the name of a method defined below-->
44
-
<button@click="greet">Greet</button>
43
+
<!-- `greet` é o nome de um método definido abaixo-->
44
+
<button@click="greet">Cumprimentar</button>
45
45
</div>
46
46
```
47
47
@@ -54,9 +54,9 @@ Vue.createApp({
54
54
},
55
55
methods: {
56
56
greet(event) {
57
-
// `this` inside methods points to the current active instance
58
-
alert('Hello'+this.name+'!')
59
-
// `event` is the native DOM event
57
+
// `this` dentro de métodos aponta para a atual instância Vue ativa
58
+
alert('Olá'+this.name+'!')
59
+
// `event` é o evento DOM nativo
60
60
if (event) {
61
61
alert(event.target.tagName)
62
62
}
@@ -65,23 +65,23 @@ Vue.createApp({
65
65
}).mount('#event-with-method')
66
66
```
67
67
68
-
Result:
68
+
Resultado:
69
69
70
-
<pclass="codepen"data-height="300"data-theme-id="39028"data-default-tab="js,result"data-user="Vue"data-slug-hash="jOPvmaX"data-editable="true"style="height: 300px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; border: 2pxsolid; margin: 1em0; padding: 1em;"data-pen-title="Event handling: with a method">
71
-
<span>See the Pen <ahref="https://codepen.io/team/Vue/pen/jOPvmaX">
72
-
Event handling: with a method</a> by Vue(<ahref="https://codepen.io/Vue">@Vue</a>)
73
-
on <ahref="https://codepen.io">CodePen</a>.</span>
70
+
<pclass="codepen"data-height="300"data-theme-id="39028"data-default-tab="js,result"data-user="vuejs-br"data-slug-hash="gOrERRW"data-editable="true"style="height: 300px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; border: 2pxsolid; margin: 1em0; padding: 1em;"data-pen-title="Exemplo de manipulação de eventos com um método">
71
+
<span>Veja o <ahref="https://codepen.io/edumedeiros/pen/gOrERRW">
72
+
Exemplo de manipulação de eventos com um método</a> por Vue.js Brasil (<ahref="https://codepen.io/vuejs-br">@vuejs-br</a>)
73
+
no <ahref="https://codepen.io">CodePen</a>.</span>
Sometimes we also need to access the original DOM event in an inline statement handler. You can pass it into a method using the special `$event` variable:
107
+
Às vezes, também precisamos acessar o evento original do DOM em um manipulador. Você pode passá-lo a um método usando a variável especial `$event`:
108
108
109
109
```html
110
-
<button@click="warn('Form cannot be submitted yet.', $event)">
111
-
Submit
110
+
<button@click="warn('O formulário ainda não pode ser enviado.', $event)">
111
+
Enviar
112
112
</button>
113
113
```
114
114
115
115
```js
116
116
// ...
117
117
methods: {
118
118
warn(message, event) {
119
-
//now we have access to the native event
119
+
//agora temos acesso ao evento nativo
120
120
if (event) {
121
121
event.preventDefault()
122
122
}
@@ -125,34 +125,34 @@ methods: {
125
125
}
126
126
```
127
127
128
-
## Multiple Event Handlers
128
+
## Múltiplos Manipuladores de Eventos
129
129
130
-
You can have multiple methods in an event handler separated by a comma operator like this:
130
+
Você pode ter vários métodos em um manipulador de eventos separados por vírgula, desta forma:
131
131
132
132
```html
133
-
<!--both one() and two() will execute on button click-->
133
+
<!--ambos one() e two() serão executados no clique do botão-->
134
134
<button@click="one($event), two($event)">
135
-
Submit
135
+
Enviar
136
136
</button>
137
137
```
138
138
139
139
```js
140
140
// ...
141
141
methods: {
142
142
one(event) {
143
-
//first handler logic...
143
+
//lógica do primeiro manipulador...
144
144
},
145
145
two(event) {
146
-
//second handler logic...
146
+
//lógica do segundo manipulador...
147
147
}
148
148
}
149
149
```
150
150
151
-
## Event Modifiers
151
+
## Modificadores de Evento
152
152
153
-
It is a very common need to call `event.preventDefault()`or`event.stopPropagation()`inside event handlers. Although we can do this easily inside methods, it would be better if the methods can be purely about data logic rather than having to deal with DOM event details.
153
+
É muito comum precisar chamar `event.preventDefault()`ou`event.stopPropagation()`em manipuladores de eventos. Embora possamos fazer isto facilmente dentro de métodos, seria melhor se os métodos pudessem lidar apenas com a lógica dos dados, em vez de ter que lidar com detalhes de eventos DOM.
154
154
155
-
To address this problem, Vue provides**event modifiers**for`v-on`. Recall that modifiers are directive postfixes denoted by a dot.
155
+
Para resolver esse problema, Vue fornece**modificadores de evento**para`v-on`. É só se lembrar que modificadores são sufixos da diretiva, denotados por um ponto.
156
156
157
157
-`.stop`
158
158
-`.prevent`
@@ -162,140 +162,140 @@ To address this problem, Vue provides **event modifiers** for `v-on`. Recall tha
162
162
-`.passive`
163
163
164
164
```html
165
-
<!--the click event's propagation will be stopped-->
165
+
<!--a propagação do evento click será interrompida-->
166
166
<a@click.stop="doThis"></a>
167
167
168
-
<!--the submit event will no longer reload the page-->
168
+
<!--o evento submit deixará de recarregar a página-->
169
169
<form@submit.prevent="onSubmit"></form>
170
170
171
-
<!--modifiers can be chained-->
171
+
<!--modificadores podem ser encadeados-->
172
172
<a@click.stop.prevent="doThat"></a>
173
173
174
-
<!--just the modifier-->
174
+
<!--é possível utilizar apenas o modificador-->
175
175
<form@submit.prevent></form>
176
176
177
-
<!--use capture mode when adding the event listener-->
178
-
<!--i.e. an event targeting an inner element is handled here before being handled by that element-->
177
+
<!--usar modo de captura ao adicionar o evento-->
178
+
<!--ou seja, um evento em um elemento interno é tratado aqui antes de ser tratado por aquele elemento-->
179
179
<div@click.capture="doThis">...</div>
180
180
181
-
<!--only trigger handler if event.target is the element itself-->
182
-
<!--i.e. not from a child element-->
181
+
<!--só aciona o manipulador se event.target é o próprio elemento-->
182
+
<!--isto é, não aciona a partir de um elemento filho-->
183
183
<div@click.self="doThat">...</div>
184
184
```
185
185
186
186
::: tip
187
-
Order matters when using modifiers because the relevant code is generated in the same order. Therefore using`@click.prevent.self`will prevent**all clicks** while`@click.self.prevent`will only prevent clicks on the element itself.
187
+
A ordem importa ao utilizar modificadores pois o código relevante é gerado na mesma ordem. Desta forma,`@click.prevent.self`irá prevenir**todos os cliques**, enquanto`@click.self.prevent`irá prevenir apenas cliques no próprio elemento.</p>
188
188
:::
189
189
190
190
```html
191
-
<!--the click event will be triggered at most once-->
191
+
<!--o evento click será disparado apenas uma vez-->
192
192
<a@click.once="doThis"></a>
193
193
```
194
194
195
-
Unlike the other modifiers, which are exclusive to native DOM events, the `.once`modifier can also be used on [component events](component-custom-events.html). If you haven't read about components yet, don't worry about this for now.
195
+
Diferente dos outros modificadores, que são exclusivos para eventos nativos, o modificador `.once`também pode ser usado em [eventos de componentes](components-custom-events.html). Se você ainda não leu sobre componentes, não se preocupe com isso neste momento.
196
196
197
-
Vue also offers the `.passive` modifier, corresponding to [`addEventListener`'s`passive`option](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Parameters).
197
+
Vue também oferece o modificador `.passive`, correspondendo à [opção`passive`do `addEventListener`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Parameters).
198
198
199
199
```html
200
-
<!--the scroll event's default behavior (scrolling) will happen-->
201
-
<!--immediately, instead of waiting for `onScroll` to complete-->
202
-
<!--in case it contains `event.preventDefault()`-->
200
+
<!--o comportamento padrão do evento _scroll_ (rolar) acontecerá-->
201
+
<!--imediatamente, ao invés de aguardar `onScroll` completar -->
202
+
<!--para descobrir se ele chama `event.preventDefault()` -->
203
203
<div@scroll.passive="onScroll">...</div>
204
204
```
205
205
206
-
The`.passive`modifier is especially useful for improving performance on mobile devices.
206
+
O`.passive`é especialmente útil para otimizar desempenho em dispositivos móveis.
207
207
208
208
::: tip
209
-
Don't use `.passive`and`.prevent`together, because`.prevent`will be ignored and your browser will probably show you a warning. Remember, `.passive`communicates to the browser that you _don't_ want to prevent the event's default behavior.
209
+
Não use `.passive`e`.prevent`juntos, pois`.prevent`será ignorado e seu navegador provavelmente exibirá um aviso. Lembre-se, `.passive`comunica ao navegador que você _não_ quer prevenir o comportamento padrão do evento.
210
210
:::
211
211
212
-
## Key Modifiers
212
+
## Modificadores de Teclado
213
213
214
-
When listening for keyboard events, we often need to check for specific keys. Vue allows adding key modifiers for `v-on`or`@`when listening for key events:
214
+
Quando escutamos eventos do teclado, precisamos muitas vezes verificar a ocorrência de teclas específicas. O Vue também permite a adição de modificadores `v-on`ou`@`ao escutar eventos de teclado:
215
215
216
216
```html
217
-
<!--only call `vm.submit()` when the `key` is `Enter` -->
217
+
<!--só chama `vm.submit()` quando o `key` é `Enter` -->
218
218
<input@keyup.enter="submit" />
219
219
```
220
220
221
-
You can directly use any valid key names exposed via [`KeyboardEvent.key`](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values)as modifiers by converting them to kebab-case.
221
+
Você pode usar diretamente qualquer nome de chave válido exposto via [`KeyboardEvent.key`](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values)como modificadores, convertendo-os em kebab-case.
222
222
223
223
```html
224
224
<input@keyup.page-down="onPageDown" />
225
225
```
226
226
227
-
In the above example, the handler will only be called if `$event.key`is equal to`'PageDown'`.
227
+
No exemplo acima, o manipulador só será chamado se `$event.key`for igual a`'PageDown'`.
228
228
229
-
### Key Aliases
229
+
### Apelidos de Teclas
230
230
231
-
Vue provides aliases for the most commonly used keys:
231
+
Vue fornece apelidos para os códigos de teclas mais comuns:
232
232
233
233
-`.enter`
234
234
-`.tab`
235
-
-`.delete` (captures both "Delete" and "Backspace" keys)
235
+
-`.delete` (captura tanto "Delete" quanto "Backspace")
236
236
-`.esc`
237
237
-`.space`
238
238
-`.up`
239
239
-`.down`
240
240
-`.left`
241
241
-`.right`
242
242
243
-
## System Modifier Keys
243
+
## Teclas Modificadoras de Sistema
244
244
245
-
You can use the following modifiers to trigger mouse or keyboard event listeners only when the corresponding modifier key is pressed:
245
+
Você pode utilizar os seguintes modificadores para acionar eventos de _mouse_ ou teclado apenas quando o modificador correspondente estiver pressionado:
246
246
247
247
-`.ctrl`
248
248
-`.alt`
249
249
-`.shift`
250
250
-`.meta`
251
251
252
-
::: tip Note
253
-
On Macintosh keyboards, meta is the command key (⌘). On Windows keyboards, meta is the Windows key (⊞). On Sun Microsystems keyboards, meta is marked as a solid diamond (◆). On certain keyboards, specifically MIT and Lisp machine keyboards and successors, such as the Knight keyboard, space-cadet keyboard, meta is labeled “META”. On Symbolics keyboards, meta is labeled “META” or “Meta”.
252
+
::: tip Nota:
253
+
Nos teclados Macintosh, meta é a tecla de comando (⌘). Nos teclados Windows, meta é a tecla Windows (⊞). Nos teclados Sun Microsystems, meta é marcada como um diamante sólido (◆). Em alguns teclados, especificamente em máquinas MIT e Lisp e suas sucessoras, assim como o teclado Knight e teclados space-cadet, meta é marcada como “META”. Em teclados Symbolics, meta é marcada como “META” ou “Meta”.
Note that modifier keys are different from regular keys and when used with `keyup` events, they have to be pressed when the event is emitted. In other words, `keyup.ctrl`will only trigger if you release a key while holding down `ctrl`. It won't trigger if you release the `ctrl`key alone
267
+
Teclas modificadoras são diferentes de teclas comuns, e quando utilizadas com eventos `keyup`, precisam estar pressionadas quando o evento é emitido. Em outras palavras, `keyup.ctrl`só vai disparar se você soltar alguma tecla enquanto ainda estiver segurando `ctrl`. E não irá disparar se você soltar a tecla `ctrl`sozinha.
268
268
:::
269
269
270
-
### `.exact` Modifier
270
+
### Modificador `.exact`
271
271
272
-
The `.exact`modifier allows control of the exact combination of system modifiers needed to trigger an event.
272
+
O modificador `.exact`permite controlar a exata combinação de modificadores de sistema que deve ser pressionada para que o gatilho dispare.
273
273
274
274
```html
275
-
<!--this will fire even if Alt or Shift is also pressed-->
275
+
<!--dispara mesmo se Alt ou Shift também estiverem pressionados-->
276
276
<button@click.ctrl="onClick">A</button>
277
277
278
-
<!--this will only fire when Ctrl and no other keys are pressed-->
278
+
<!--dispara somente quando Ctrl (e nenhuma outra tecla) for pressionado-->
279
279
<button@click.ctrl.exact="onCtrlClick">A</button>
280
280
281
-
<!--this will only fire when no system modifiers are pressed-->
281
+
<!--dispara somente se não houverem teclas modificadoras sistema pressionadas-->
282
282
<button@click.exact="onClick">A</button>
283
283
```
284
284
285
-
### Mouse Button Modifiers
285
+
### Modificadores dos Botões do Mouse
286
286
287
287
-`.left`
288
288
-`.right`
289
289
-`.middle`
290
290
291
-
These modifiers restrict the handler to events triggered by a specific mouse button.
291
+
Estes modificadores restringem o manipulador a eventos disparados por um botão específico do _mouse_.
292
292
293
-
## Why Listeners in HTML?
293
+
## Por Que Escutas no HTML?
294
294
295
-
You might be concerned that this whole event listening approach violates the good old rules about "separation of concerns". Rest assured - since all Vue handler functions and expressions are strictly bound to the ViewModel that's handling the current view, it won't cause any maintenance difficulty. In fact, there are several benefits in using `v-on`or`@`:
295
+
Você pode estar pensando que esta abordagem de escutas de evento viola as boas e velhas práticas sobre "separação de responsabilidades". Fique tranquilo - como todas as funções de manipuladores e expressões Vue são estritamente ligadas ao _ViewModel_ que está manipulando o modo de exibição atual, essa abordagem não causará qualquer dificuldade de manutenção. Na verdade, há vários benefícios em usar `v-on`ou`@`:
296
296
297
-
1.It's easier to locate the handler function implementations within your JS code by skimming the HTML template.
297
+
1.É mais fácil localizar as implementações de função de manipulador dentro de seu código JS percorrendo o _template_ HTML.
298
298
299
-
2.Since you don't have to manually attach event listeners in JS, your ViewModel code can be pure logic and DOM-free. This makes it easier to test.
299
+
2.Como você não tem que manualmente anexar escutas a eventos em JS, seu código de _ViewModel_ pode conter apenas a lógica pura e está livre de manipulação DOM. Isto torna mais fácil de testar.
300
300
301
-
3.When a ViewModel is destroyed, all event listeners are automatically removed. You don't need to worry about cleaning it up yourself.
301
+
3.Quando um _ViewModel_ é destruído, todas escutas a eventos são removidas automaticamente. Você não precisa se preocupar em removê-las explicitamente.
0 commit comments