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
In addition to the default set of directives shipped in core (like`v-model`or`v-show`), Vue also allows you to register your own custom directives. Note that in Vue, the primary form of code reuse and abstraction is components - however, there may be cases where you need some low-level DOM access on plain elements, and this is where custom directives would still be useful. An example would be focusing on an input element, like this one:
5
+
Em adição ao conjunto de diretivas existente por padrão em seu núcleo (como`v-model`ou`v-show`), o Vue te possibilita registrar diretivas customizadas. Note que no Vue, a forma primária de reuso e abstração de código são os componentes - no entanto, pode haver casos em que você precise um acesso de nível mais baixo aos elementos no DOM, e é aqui que as diretivas customizadas são úteis. Um exemplo seria acionar o foco em um elemento `input`, como esse:
When the page loads, that element gains focus (note: `autofocus` doesn't work on mobile Safari). In fact, if you haven't clicked on anything else since visiting this page, the input above should be focused now. Also, you can click on the`Rerun`button and input will be focused.
9
+
Quando a página carrega, o elemento ganha o foco (nota: o atributo nativo autofocus não funciona no Safari para dispositivos móveis). Na verdade, se você não clicou em nada desde que visitou essa página, o input acima deve estar focado agora. Além disso, você pode clicar no botão`Rerun`e o input vai ganhar foco.
10
10
11
-
Now let's build the directive that accomplishes this:
11
+
Agora vamos construir a diretiva que faz isso:
12
12
13
13
```js
14
14
constapp=Vue.createApp({})
15
-
//Register a global custom directive called `v-focus`
15
+
//Registra uma diretiva customizada global chamada `v-focus`
16
16
app.directive('focus', {
17
-
//When the bound element is mounted into the DOM...
17
+
//Quando o elemento vinculado é inserido no DOM
18
18
mounted(el) {
19
-
//Focus the element
19
+
//Foca o elemento
20
20
el.focus()
21
21
}
22
22
})
23
23
```
24
24
25
-
If you want to register a directive locally instead, components also accept a `directives` option:
25
+
Se você deseja registrar uma diretiva local em vez disso, os componentes também aceitam a opção `directives`:
26
26
27
27
```js
28
28
directives: {
29
29
focus: {
30
-
//directive definition
30
+
//definição da diretiva
31
31
mounted(el) {
32
32
el.focus()
33
33
}
34
34
}
35
35
}
36
36
```
37
37
38
-
Then in a template, you can use the new `v-focus`attribute on any element, like this:
38
+
Então no *template*, você pode usar o novo atributo `v-focus`em qualquer elemento, por exemplo:
39
39
40
40
```html
41
41
<inputv-focus />
42
42
```
43
43
44
-
## Hook Functions
44
+
## Funções de Gatilhos (Hook Functions)
45
45
46
-
A directive definition object can provide several hook functions (all optional):
46
+
As funções de hook são as funções que são executadas conforme o estado da diretiva e há uma variedade disponível para uso (todas opcionais):
47
47
48
-
-`created`: called before the bound element's attributes or event listeners are applied. This is useful in cases where the directive needs to attach event listeners that must be called before normal `v-on`event listeners.
48
+
-`created`: Executa antes que os atributos do elemento vinculado ou ouvintes de evento sejam aplicados. Isso é útil nos casos em que a diretiva precisa anexar ouvintes de eventos que devem ser chamados antes dos ouvintes de eventos `v-on`normais.
49
49
50
-
-`beforeMount`: called when the directive is first bound to the element and before parent component is mounted.
50
+
-`beforeMount`: Executa quando a diretiva é ligada pela primeira vez ao elemento e antes que o componente pai seja montado. Aí é onde você pode fazer o trabalho de configuração inicial.
51
51
52
-
-`mounted`: called when the bound element's parent component is mounted.
52
+
-`mounted`: Executa quando o componente pai do elemento ligado é montado.
53
53
54
-
-`beforeUpdate`: called before the containing component's VNode is updated
54
+
-`beforeUpdate`: Executa antes que o VNode contido no componente seja atualizado.
55
55
56
-
:::tip Note
57
-
We'll cover VNodes in more detail [later](render-function.html#the-virtual-dom-tree), when we discuss render functions.
56
+
:::tip Nota
57
+
Vamos cobrir VNodes com mais detalhes [depois](render-function.html#the-virtual-dom-tree), quando discutirmos as funções de renderização (render functions).
58
58
:::
59
59
60
-
-`updated`: called after the containing component's VNode **and the VNodes of its children**have updated.
60
+
-`updated`: Executado após o VNode contido no componente **e os VNodes de seus filhos**terem sido atualizados.
61
61
62
-
-`beforeUnmount`: called before the bound element's parent component is unmounted
62
+
-`beforeUnmount`: Executado antes do pai dos elementos ligados sejam desmontados.
63
63
64
-
-`unmounted`: called only once, when the directive is unbound from the element and the parent component is unmounted.
64
+
-`unmounted`: Executado apenas uma vez, quando a diretiva é desligada do elemento e o componente pai é desmontado
65
65
66
-
You can check the arguments passed into these hooks (i.e.`el`, `binding`, `vnode`, and `prevVnode`) in [Custom Directive API](../api/application-api.html#directive)
66
+
Você pode checar os argumentos que foram passados para esses hooks (ex:`el`, `binding`, `vnode` e `prevNode`) em [API de Diretivas Customizadas](../api/application-api.html#directive)
67
67
68
-
### Dynamic Directive Arguments
68
+
### Argumentos Dinâmicos de Diretiva
69
69
70
-
Directive arguments can be dynamic. For example, in`v-mydirective:[argument]="value"`, the`argument`can be updated based on data properties in our component instance! This makes our custom directives flexible for use throughout our application.
70
+
Os argumentos da diretiva podem ser dinâmicos. Por exemplo, em`v-mydirective:[argument]="value"`, o`argument`pode ser atualizado baseada nas propriedades de dados na nossa instância do componente! Isso faz nossas diretivas customizadas flexíveis para utilizar na aplicação.
71
71
72
-
Let's say you want to make a custom directive that allows you to pin elements to your page using fixed positioning. We could create a custom directive where the value updates the vertical positioning in pixels, like this:
72
+
Digamos que você queira fazer uma diretiva customizada que permite "pregar" elementos na sua página utilizando posicionamento fixo. Nós poderiamos criar uma diretiva customizada onde o valor atualiza a posição vertical em pixels, desse jeito:
73
73
74
74
```vue-html
75
75
<div id="dynamic-arguments-example" class="demo">
76
-
<p>Scroll down the page</p>
77
-
<p v-pin="200">Stick me 200px from the top of the page</p>
76
+
<p>Role para baixo</p>
77
+
<p v-pin="200">Me pregue 200px do topo da página</p>
78
78
</div>
79
79
```
80
80
@@ -84,20 +84,20 @@ const app = Vue.createApp({})
84
84
app.directive('pin', {
85
85
mounted(el, binding) {
86
86
el.style.position='fixed'
87
-
// binding.value is the value we pass to directive - in this case, it's 200
87
+
// binding.value é o valor que vamos passar para a diretiva - nesse caso, é 200.
88
88
el.style.top=binding.value+'px'
89
89
}
90
90
})
91
91
92
92
app.mount('#dynamic-arguments-example')
93
93
```
94
94
95
-
This would pin the element 200px from the top of the page. But what happens if we run into a scenario when we need to pin the element from the left, instead of the top? Here's where a dynamic argument that can be updated per component instance comes in very handy:
95
+
Isso iria pregar o elemento 200px do topo da página. Mas o que acontece quando encontramos um cenário que precisamos pregar um elemento da esquerda, ao invés do topo? É aqui que os argumentos dinâmicos que podem ser atualizados por instância de componente são úteis:
96
96
97
97
```vue-html
98
98
<div id="dynamicexample">
99
-
<h3>Scroll down inside this section ↓</h3>
100
-
<p v-pin:[direction]="200">I am pinned onto the page at 200px to the left.</p>
99
+
<h3>Role para baixo nessa seção ↓</h3>
100
+
<p v-pin:[direction]="200">Estou pregado na página 200px à esquerda.</p>
101
101
</div>
102
102
```
103
103
@@ -113,26 +113,26 @@ const app = Vue.createApp({
113
113
app.directive('pin', {
114
114
mounted(el, binding) {
115
115
el.style.position='fixed'
116
-
// binding.arg is an argument we pass to directive
116
+
// binding.arg é um argumento que passamos para a diretiva
Our custom directive is now flexible enough to support a few different use cases. To make it even more dynamic, we can also allow to modify a bound value. Let's create an additional property`pinPadding`and bind it to the`<input type="range">`
129
+
A nossa diretiva customizada agora está flexível o suficiente para atender a vários casos diferentes. Para deixá-lo mais dinâmico, podemos possibilitar alterar um valor vinculado. Vamos criar uma propriedade adicional`pinPadding`e vincular ao`<input type="range">`
In previous example, you may want the same behavior on`mounted`and`updated`, but don't care about the other hooks. You can do it by passing the callback to directive:
172
+
No exemplo anterior, você pode desejar o mesmo comportamento no`mounted`e`updated`, mas não liga para os outros gatilhos. Você pode fazer isso passando a *callback* para a diretiva:
If your directive needs multiple values, you can also pass in a JavaScript object literal. Remember, directives can take any valid JavaScript expression.
184
+
Se a sua diretiva precisa de múltiplos valores, você também pode passar um objeto literal do javascript. Lembre-se que as diretivas pode receber qualquer expressão Javascript válida.
When used on components, custom directive will always apply to component's root node, similarly to [non-prop attributes](component-attrs.html).
199
+
Quando usada em componentes, a diretiva customizada sempre se aplicará ao nó raiz do componente, de forma semelhante a [atributos não-prop](component-attrs.html).
200
200
201
201
```vue-html
202
202
<my-component v-demo="test"></my-component>
@@ -205,13 +205,13 @@ When used on components, custom directive will always apply to component's root
205
205
```js
206
206
app.component('my-component', {
207
207
template:`
208
-
<div> // v-demo directive will be applied here
209
-
<span>My component content</span>
208
+
<div> // a diretiva v-demo será aplicada aqui
209
+
<span>Conteúdo do meu componente</span>
210
210
</div>
211
211
`
212
212
})
213
213
```
214
214
215
-
Unlike attributes, directives can't be passed to a different element with`v-bind="$attrs"`.
215
+
Ao contrário dos atributos, as diretivas não podem ser passadas para um elemento diferente com`v-bind="$attrs"`.
216
216
217
-
With [fragments](/guide/migration/fragments.html#overview) support, components can potentially have more than one root nodes. When applied to a multi-root component, directive will be ignored and the warning will be thrown.
217
+
Com o suporte de [fragmentos](/guide/migration/fragments.html#visao-geral), os componentes podem ter potencialmente mais de um nó raiz. Quando aplicada a um componente de múltiplas raízes, a diretiva será ignorada e o aviso será lançado.
0 commit comments