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="nomeDoMétodo"`ou com o atalho, `@click="nomeDoMétodo"`
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>
<common-codepen-snippettitle="Exemplo básico de manipulação de eventos"slug="YzqMRBW" />
34
29
35
-
## Method Event Handlers
30
+
## Métodos em Manipuladores
36
31
37
-
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.
32
+
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
33
39
-
For example:
34
+
Por Exemplo:
40
35
41
36
```html
42
37
<divid="event-with-method">
43
-
<!-- `greet` is the name of a method defined below-->
44
-
<button@click="greet">Greet</button>
38
+
<!-- `greet` é o nome de um método definido abaixo-->
39
+
<button@click="greet">Cumprimentar</button>
45
40
</div>
46
41
```
47
42
@@ -54,9 +49,9 @@ Vue.createApp({
54
49
},
55
50
methods: {
56
51
greet(event) {
57
-
// `this` inside methods points to the current active instance
58
-
alert('Hello'+this.name+'!')
59
-
// `event` is the native DOM event
52
+
// `this` dentro de métodos aponta para a atual instância Vue ativa
53
+
alert('Olá'+this.name+'!')
54
+
// `event` é o evento DOM nativo
60
55
if (event) {
61
56
alert(event.target.tagName)
62
57
}
@@ -65,23 +60,18 @@ Vue.createApp({
65
60
}).mount('#event-with-method')
66
61
```
67
62
68
-
Result:
63
+
Resultado:
69
64
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>
<common-codepen-snippettitle="Exemplo de evento com chamada direta de métodoo"slug="mdPgQvR" />
106
91
107
-
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:
92
+
Às vezes, também precisamos acessar o evento original do DOM em um manipulador. Você pode passá-lo à um método usando a variável especial `$event`:
108
93
109
94
```html
110
-
<button@click="warn('Form cannot be submitted yet.', $event)">
111
-
Submit
95
+
<button@click="warn('O formulário ainda não pode ser enviado.', $event)">
96
+
Enviar
112
97
</button>
113
98
```
114
99
115
100
```js
116
101
// ...
117
102
methods: {
118
103
warn(message, event) {
119
-
//now we have access to the native event
104
+
//agora temos acesso ao evento nativo
120
105
if (event) {
121
106
event.preventDefault()
122
107
}
@@ -125,34 +110,34 @@ methods: {
125
110
}
126
111
```
127
112
128
-
## Multiple Event Handlers
113
+
## Múltiplos Manipuladores de Eventos
129
114
130
-
You can have multiple methods in an event handler separated by a comma operator like this:
115
+
Você pode ter vários métodos em um manipulador de eventos separados por vírgula, desta forma:
131
116
132
117
```html
133
-
<!--both one() and two() will execute on button click-->
118
+
<!--ambos one() e two() serão executados no clique do botão-->
134
119
<button@click="one($event), two($event)">
135
-
Submit
120
+
Enviar
136
121
</button>
137
122
```
138
123
139
124
```js
140
125
// ...
141
126
methods: {
142
127
one(event) {
143
-
//first handler logic...
128
+
//lógica do primeiro manipulador...
144
129
},
145
130
two(event) {
146
-
//second handler logic...
131
+
//lógica do segundo manipulador...
147
132
}
148
133
}
149
134
```
150
135
151
-
## Event Modifiers
136
+
## Modificadores de Evento
152
137
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.
138
+
É 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
139
155
-
To address this problem, Vue provides**event modifiers**for`v-on`. Recall that modifiers are directive postfixes denoted by a dot.
140
+
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
141
157
142
-`.stop`
158
143
-`.prevent`
@@ -162,140 +147,140 @@ To address this problem, Vue provides **event modifiers** for `v-on`. Recall tha
162
147
-`.passive`
163
148
164
149
```html
165
-
<!--the click event's propagation will be stopped-->
150
+
<!--a propagação do evento click será interrompida-->
166
151
<a@click.stop="doThis"></a>
167
152
168
-
<!--the submit event will no longer reload the page-->
153
+
<!--o evento submit deixará de recarregar a página-->
169
154
<form@submit.prevent="onSubmit"></form>
170
155
171
-
<!--modifiers can be chained-->
156
+
<!--modificadores podem ser encadeados-->
172
157
<a@click.stop.prevent="doThat"></a>
173
158
174
-
<!--just the modifier-->
159
+
<!--é possível utilizar apenas o modificador-->
175
160
<form@submit.prevent></form>
176
161
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-->
162
+
<!--usar modo de captura ao adicionar o evento-->
163
+
<!--ou seja, um evento em um elemento interno é tratado aqui antes de ser tratado por aquele elemento-->
179
164
<div@click.capture="doThis">...</div>
180
165
181
-
<!--only trigger handler if event.target is the element itself-->
182
-
<!--i.e. not from a child element-->
166
+
<!--só aciona o manipulador se event.target é o próprio elemento-->
167
+
<!--isto é, não aciona a partir de um elemento filho-->
183
168
<div@click.self="doThat">...</div>
184
169
```
185
170
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.
171
+
::: tip Nota
172
+
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.
188
173
:::
189
174
190
175
```html
191
-
<!--the click event will be triggered at most once-->
176
+
<!--o evento click será disparado apenas uma vez-->
192
177
<a@click.once="doThis"></a>
193
178
```
194
179
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.
180
+
Diferente dos outros modificadores, que são exclusivos para eventos nativos, o modificador `.once`também pode ser usado em [eventos de componentes](component-custom-events.html). Se você ainda não leu sobre componentes, não se preocupe com isso neste momento.
196
181
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).
182
+
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
183
199
184
```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()`-->
185
+
<!--o comportamento padrão do evento _scroll_ (rolar) acontecerá-->
186
+
<!--imediatamente, ao invés de aguardar `onScroll` completar -->
187
+
<!--para descobrir se ele chama `event.preventDefault()` -->
203
188
<div@scroll.passive="onScroll">...</div>
204
189
```
205
190
206
-
The`.passive`modifier is especially useful for improving performance on mobile devices.
191
+
O`.passive`é especialmente útil para otimizar desempenho em dispositivos móveis.
207
192
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.
193
+
::: tip Nota
194
+
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
195
:::
211
196
212
-
## Key Modifiers
197
+
## Modificadores de Teclado
213
198
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:
199
+
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
200
216
201
```html
217
-
<!--only call `vm.submit()` when the `key` is `Enter` -->
202
+
<!--só chama `vm.submit()` quando o `key` é `Enter` -->
218
203
<input@keyup.enter="submit" />
219
204
```
220
205
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.
206
+
Você pode usar diretamente qualquer nome de tecla 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
207
223
208
```html
224
209
<input@keyup.page-down="onPageDown" />
225
210
```
226
211
227
-
In the above example, the handler will only be called if `$event.key`is equal to`'PageDown'`.
212
+
No exemplo acima, o manipulador só será chamado se `$event.key`for igual a`'PageDown'`.
228
213
229
-
### Key Aliases
214
+
### Apelidos de Teclas
230
215
231
-
Vue provides aliases for the most commonly used keys:
216
+
Vue fornece apelidos para os códigos de teclas mais comuns:
232
217
233
218
-`.enter`
234
219
-`.tab`
235
-
-`.delete` (captures both "Delete" and "Backspace" keys)
220
+
-`.delete` (captura tanto "Delete" quanto "Backspace")
236
221
-`.esc`
237
222
-`.space`
238
223
-`.up`
239
224
-`.down`
240
225
-`.left`
241
226
-`.right`
242
227
243
-
## System Modifier Keys
228
+
## Modificadores de Teclas do Sistema
244
229
245
-
You can use the following modifiers to trigger mouse or keyboard event listeners only when the corresponding modifier key is pressed:
230
+
Você pode utilizar os seguintes modificadores para acionar eventos de _mouse_ ou teclado apenas quando o modificador correspondente estiver pressionado:
246
231
247
232
-`.ctrl`
248
233
-`.alt`
249
234
-`.shift`
250
235
-`.meta`
251
236
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”.
237
+
::: tip Nota
238
+
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
252
+
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
253
:::
269
254
270
-
### `.exact` Modifier
255
+
### Modificador `.exact`
271
256
272
-
The `.exact`modifier allows control of the exact combination of system modifiers needed to trigger an event.
257
+
O modificador `.exact`permite controlar a exata combinação de modificadores de sistema que deve ser pressionada para que o gatilho dispare.
273
258
274
259
```html
275
-
<!--this will fire even if Alt or Shift is also pressed-->
260
+
<!--dispara mesmo se Alt ou Shift também estiverem pressionados-->
276
261
<button@click.ctrl="onClick">A</button>
277
262
278
-
<!--this will only fire when Ctrl and no other keys are pressed-->
263
+
<!--dispara somente quando Ctrl (e nenhuma outra tecla) for pressionado-->
279
264
<button@click.ctrl.exact="onCtrlClick">A</button>
280
265
281
-
<!--this will only fire when no system modifiers are pressed-->
266
+
<!--dispara somente se não houverem teclas do sistema pressionadas-->
282
267
<button@click.exact="onClick">A</button>
283
268
```
284
269
285
-
### Mouse Button Modifiers
270
+
### Modificadores dos Botões do Mouse
286
271
287
272
-`.left`
288
273
-`.right`
289
274
-`.middle`
290
275
291
-
These modifiers restrict the handler to events triggered by a specific mouse button.
276
+
Estes modificadores restringem o manipulador à eventos disparados por um botão específico do _mouse_.
292
277
293
-
## Why Listeners in HTML?
278
+
## Por Que Escutas no HTML?
294
279
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`@`:
280
+
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
281
297
-
1.It's easier to locate the handler function implementations within your JS code by skimming the HTML template.
282
+
1.É mais fácil localizar as implementações de função de manipulador dentro de seu código JS percorrendo o _template_ HTML.
298
283
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.
284
+
2.Como você não tem que manualmente anexar escutas à eventos em JS, seu código de _ViewModel_ pode conter apenas a lógica pura e ser livre de manipulação do DOM. Isto torna mais fácil de testar.
300
285
301
-
3.When a ViewModel is destroyed, all event listeners are automatically removed. You don't need to worry about cleaning it up yourself.
286
+
3.Quando um _ViewModel_ é destruído, todas as escutas de eventos são removidas automaticamente. Você não precisa se preocupar em removê-las explicitamente.
0 commit comments