Skip to content

Commit efbe0d7

Browse files
authored
Merge pull request #43 from dumedeiros/dumedeiros-events
docs: translate "guide/events.md" #9
2 parents c039c8c + aa669ac commit efbe0d7

File tree

1 file changed

+83
-98
lines changed

1 file changed

+83
-98
lines changed

src/guide/events.md

Lines changed: 83 additions & 98 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
1-
# Event Handling
1+
# Manipulação de Eventos
22

3-
## Listening to Events
3+
## Escutando Eventos
44

5-
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"`
66

7-
For example:
7+
Por exemplo:
88

99
```html
1010
<div id="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>
1313
</div>
1414
```
1515

@@ -23,25 +23,20 @@ Vue.createApp({
2323
}).mount('#basic-event')
2424
```
2525

26-
Result:
26+
Resultado:
2727

28-
<p class="codepen" data-height="300" data-theme-id="39028" data-default-tab="html,result" data-user="Vue" data-slug-hash="xxGadPZ" data-editable="true" style="height: 300px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; border: 2px solid; margin: 1em 0; padding: 1em;" data-pen-title="Event handling: basic">
29-
<span>See the Pen <a href="https://codepen.io/team/Vue/pen/xxGadPZ">
30-
Event handling: basic</a> by Vue (<a href="https://codepen.io/Vue">@Vue</a>)
31-
on <a href="https://codepen.io">CodePen</a>.</span>
32-
</p>
33-
<script async src="https://static.codepen.io/assets/embed/ei.js"></script>
28+
<common-codepen-snippet title="Exemplo básico de manipulação de eventos" slug="YzqMRBW" />
3429

35-
## Method Event Handlers
30+
## Métodos em Manipuladores
3631

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.
3833

39-
For example:
34+
Por Exemplo:
4035

4136
```html
4237
<div id="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>
4540
</div>
4641
```
4742

@@ -54,9 +49,9 @@ Vue.createApp({
5449
},
5550
methods: {
5651
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
6055
if (event) {
6156
alert(event.target.tagName)
6257
}
@@ -65,23 +60,18 @@ Vue.createApp({
6560
}).mount('#event-with-method')
6661
```
6762

68-
Result:
63+
Resultado:
6964

70-
<p class="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: 2px solid; margin: 1em 0; padding: 1em;" data-pen-title="Event handling: with a method">
71-
<span>See the Pen <a href="https://codepen.io/team/Vue/pen/jOPvmaX">
72-
Event handling: with a method</a> by Vue (<a href="https://codepen.io/Vue">@Vue</a>)
73-
on <a href="https://codepen.io">CodePen</a>.</span>
74-
</p>
75-
<script async src="https://static.codepen.io/assets/embed/ei.js"></script>
65+
<common-codepen-snippet title="Exemplo de manipulação de eventos com um método" slug="RwaOqvo" />
7666

77-
## Methods in Inline Handlers
67+
## Chamada Direta de Métodos
7868

79-
Instead of binding directly to a method name, we can also use methods in an inline JavaScript statement:
69+
Em vez de interligar o evento diretamente ao nome de um método, também podemos chamar métodos diretamente com uma instrução JavaScript:
8070

8171
```html
8272
<div id="inline-handler">
83-
<button @click="say('hi')">Say hi</button>
84-
<button @click="say('what')">Say what</button>
73+
<button @click="say('oi')">Diga oi</button>
74+
<button @click="say('tchau')">Diga tchau</button>
8575
</div>
8676
```
8777

@@ -95,28 +85,23 @@ Vue.createApp({
9585
}).mount('#inline-handler')
9686
```
9787

98-
Result:
88+
Resultado:
9989

100-
<p class="codepen" data-height="300" data-theme-id="39028" data-default-tab="html,result" data-user="Vue" data-slug-hash="WNvgjda" data-editable="true" style="height: 300px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; border: 2px solid; margin: 1em 0; padding: 1em;" data-pen-title="Event handling: with an inline handler">
101-
<span>See the Pen <a href="https://codepen.io/team/Vue/pen/WNvgjda">
102-
Event handling: with an inline handler</a> by Vue (<a href="https://codepen.io/Vue">@Vue</a>)
103-
on <a href="https://codepen.io">CodePen</a>.</span>
104-
</p>
105-
<script async src="https://static.codepen.io/assets/embed/ei.js"></script>
90+
<common-codepen-snippet title="Exemplo de evento com chamada direta de métodoo" slug="mdPgQvR" />
10691

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`:
10893

10994
```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
11297
</button>
11398
```
11499

115100
```js
116101
// ...
117102
methods: {
118103
warn(message, event) {
119-
// now we have access to the native event
104+
// agora temos acesso ao evento nativo
120105
if (event) {
121106
event.preventDefault()
122107
}
@@ -125,34 +110,34 @@ methods: {
125110
}
126111
```
127112

128-
## Multiple Event Handlers
113+
## Múltiplos Manipuladores de Eventos
129114

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:
131116

132117
```html
133-
<!-- both one() and two() will execute on button click -->
118+
<!-- ambos one() e two() serão executados no clique do botão -->
134119
<button @click="one($event), two($event)">
135-
Submit
120+
Enviar
136121
</button>
137122
```
138123

139124
```js
140125
// ...
141126
methods: {
142127
one(event) {
143-
// first handler logic...
128+
// lógica do primeiro manipulador...
144129
},
145130
two(event) {
146-
// second handler logic...
131+
// lógica do segundo manipulador...
147132
}
148133
}
149134
```
150135

151-
## Event Modifiers
136+
## Modificadores de Evento
152137

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.
154139

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.
156141

157142
- `.stop`
158143
- `.prevent`
@@ -162,140 +147,140 @@ To address this problem, Vue provides **event modifiers** for `v-on`. Recall tha
162147
- `.passive`
163148

164149
```html
165-
<!-- the click event's propagation will be stopped -->
150+
<!-- a propagação do evento click será interrompida -->
166151
<a @click.stop="doThis"></a>
167152

168-
<!-- the submit event will no longer reload the page -->
153+
<!-- o evento submit deixará de recarregar a página -->
169154
<form @submit.prevent="onSubmit"></form>
170155

171-
<!-- modifiers can be chained -->
156+
<!-- modificadores podem ser encadeados -->
172157
<a @click.stop.prevent="doThat"></a>
173158

174-
<!-- just the modifier -->
159+
<!-- é possível utilizar apenas o modificador -->
175160
<form @submit.prevent></form>
176161

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 -->
179164
<div @click.capture="doThis">...</div>
180165

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 -->
183168
<div @click.self="doThat">...</div>
184169
```
185170

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.
188173
:::
189174

190175
```html
191-
<!-- the click event will be triggered at most once -->
176+
<!-- o evento click será disparado apenas uma vez -->
192177
<a @click.once="doThis"></a>
193178
```
194179

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.
196181

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).
198183

199184
```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()` -->
203188
<div @scroll.passive="onScroll">...</div>
204189
```
205190

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.
207192

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.
210195
:::
211196

212-
## Key Modifiers
197+
## Modificadores de Teclado
213198

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:
215200

216201
```html
217-
<!-- only call `vm.submit()` when the `key` is `Enter` -->
202+
<!-- só chama `vm.submit()` quando o `key` é `Enter` -->
218203
<input @keyup.enter="submit" />
219204
```
220205

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.
222207

223208
```html
224209
<input @keyup.page-down="onPageDown" />
225210
```
226211

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'`.
228213

229-
### Key Aliases
214+
### Apelidos de Teclas
230215

231-
Vue provides aliases for the most commonly used keys:
216+
Vue fornece apelidos para os códigos de teclas mais comuns:
232217

233218
- `.enter`
234219
- `.tab`
235-
- `.delete` (captures both "Delete" and "Backspace" keys)
220+
- `.delete` (captura tanto "Delete" quanto "Backspace")
236221
- `.esc`
237222
- `.space`
238223
- `.up`
239224
- `.down`
240225
- `.left`
241226
- `.right`
242227

243-
## System Modifier Keys
228+
## Modificadores de Teclas do Sistema
244229

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:
246231

247232
- `.ctrl`
248233
- `.alt`
249234
- `.shift`
250235
- `.meta`
251236

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”.
254239
:::
255240

256-
For example:
241+
Por exemplo:
257242

258243
```html
259244
<!-- Alt + Enter -->
260245
<input @keyup.alt.enter="clear" />
261246

262247
<!-- Ctrl + Click -->
263-
<div @click.ctrl="doSomething">Do something</div>
248+
<div @click.ctrl="doSomething">Faça alguma coisa</div>
264249
```
265250

266251
::: tip
267-
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.
268253
:::
269254

270-
### `.exact` Modifier
255+
### Modificador `.exact`
271256

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.
273258

274259
```html
275-
<!-- this will fire even if Alt or Shift is also pressed -->
260+
<!-- dispara mesmo se Alt ou Shift também estiverem pressionados -->
276261
<button @click.ctrl="onClick">A</button>
277262

278-
<!-- this will only fire when Ctrl and no other keys are pressed -->
263+
<!-- dispara somente quando Ctrl (e nenhuma outra tecla) for pressionado -->
279264
<button @click.ctrl.exact="onCtrlClick">A</button>
280265

281-
<!-- this will only fire when no system modifiers are pressed -->
266+
<!-- dispara somente se não houverem teclas do sistema pressionadas -->
282267
<button @click.exact="onClick">A</button>
283268
```
284269

285-
### Mouse Button Modifiers
270+
### Modificadores dos Botões do Mouse
286271

287272
- `.left`
288273
- `.right`
289274
- `.middle`
290275

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_.
292277

293-
## Why Listeners in HTML?
278+
## Por Que Escutas no HTML?
294279

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 `@`:
296281

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.
298283

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.
300285

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

Comments
 (0)