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
Fora o conjunto de diretivas padrão existente por padrão no core (tipo `v-model` ou `v-show`), o Vue também 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 de input, como esse:
4
6
5
-
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:
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.
15
+
Quando a página carregar , o elemento é focado (nota: o `autofocus`não funciona no Safari de mobile). 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.
15
16
16
-
Now let's build the directive that accomplishes this:
17
+
Agora vamos construir a diretiva que faz isso:
17
18
18
19
```js
19
20
constapp=Vue.createApp({})
20
-
//Register a global custom directive called `v-focus`
21
+
//Registar uma diretiva customizada e global chamada `v-focus`
21
22
app.directive('focus', {
22
-
//When the bound element is mounted into the DOM...
23
+
//Quando o elemento é montado ao DOM
23
24
mounted(el) {
24
-
//Focus the element
25
+
//Foca o elemento
25
26
el.focus()
26
27
}
27
28
})
28
29
```
29
-
30
-
If you want to register a directive locally instead, components also accept a `directives` option:
30
+
Se você quer registrar uma diretiva local, os componentes também aceitam a opção `directives`:
31
31
32
32
```js
33
33
directives: {
34
34
focus: {
35
-
//directive definition
35
+
//definição da diretiva
36
36
mounted(el) {
37
37
el.focus()
38
38
}
39
39
}
40
40
}
41
41
```
42
42
43
-
Then in a template, you can use the new `v-focus`attribute on any element, like this:
43
+
Então no template, você pode usar o novo atributo `v-focus`em qualquer elemento, tipo assim:
44
44
45
45
```html
46
46
<inputv-focus />
47
47
```
48
48
49
-
## Hook Functions
49
+
## Funções de hook (Hook Functions)
50
+
51
+
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):
50
52
51
-
A directive definition object can provide several hook functions (all optional):
53
+
-`beforeMount`: Executa quando a diretiva é ligada pela primeira vez ao elemento e antes que o componente pai seja montado. É aqui que você faz a configuração que é feita uma vez apenas.
52
54
53
-
-`beforeMount`: called when the directive is first bound to the element and before parent component is mounted. This is where you can do one-time setup work.
55
+
-`mounted`: Executa quando o componente pai do elemento ligado é montado.
54
56
55
-
-`mounted`: called when the bound element's parent component is mounted.
57
+
-`beforeUpdate`: Executa antes que os VNode contido no componente são atualizados.
56
58
57
-
-`beforeUpdate`: called before the containing component's VNode is updated
59
+
> Nota:
60
+
> 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
61
59
-
:::tip Note
60
-
We'll cover VNodes in more detail [later](render-function.html#the-virtual-dom-tree), when we discuss render functions.
61
-
:::
62
62
63
-
-`updated`: called after the containing component's VNode **and the VNodes of its children**have updated.
63
+
-`updated`: Executado após os VNodes contidos no componente **e os filhos desses VNodes**terem sido atualizados.
64
64
65
-
-`beforeUnmount`: called before the bound element's parent component is unmounted
65
+
-`beforeUnmount`: Executado antes do pai dos elementos ligados sejam desmontados.
66
66
67
-
-`unmounted`: called only once, when the directive is unbound from the element and the parent component is unmounted.
67
+
-`unmounted`: Executado apenas uma vez, quando a diretiva é desligada do elemento e o componente pai é desmontado
68
68
69
-
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)
69
+
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)
70
70
71
-
### Dynamic Directive Arguments
71
+
### Argumentos dinâmicos da diretiva
72
72
73
-
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.
73
+
Os argumentos da diretiva podem ser dinâmicos. Por exemplo, em`v-minhadiretiva:[argumento]="valor"`, o `argumento` 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.
74
74
75
-
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:
75
+
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:
76
76
77
77
```vue-html
78
-
<div id="dynamic-arguments-example" class="demo">
79
-
<p>Scroll down the page</p>
80
-
<p v-pin="200">Stick me 200px from the top of the page</p>
<p v-pin="200">Me pregue 200px do topo da página</p>
81
81
</div>
82
82
```
83
83
@@ -87,20 +87,20 @@ const app = Vue.createApp({})
87
87
app.directive('pin', {
88
88
mounted(el, binding) {
89
89
el.style.position='fixed'
90
-
// binding.value is the value we pass to directive - in this case, it's 200
90
+
// binding.value é o valor que vamos passar para a diretiva - nesse caso, é 200.
91
91
el.style.top=binding.value+'px'
92
92
}
93
93
})
94
94
95
-
app.mount('#dynamic-arguments-example')
95
+
app.mount('#exemplo-argumentos-dinamicos')
96
96
```
97
97
98
-
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:
98
+
Isso iria pregar o elemento 200 px 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:
99
99
100
100
```vue-html
101
-
<div id="dynamicexample">
102
-
<h3>Scroll down inside this section ↓</h3>
103
-
<p v-pin:[direction]="200">I am pinned onto the page at 200px to the left.</p>
101
+
<div id="exemplodinamico">
102
+
<h3>Role para baixo nessa seção ↓</h3>
103
+
<p v-pin:[direction]="200">Estou pregado na página a 200 px para a esquerda.</p>
104
104
</div>
105
105
```
106
106
@@ -116,31 +116,31 @@ const app = Vue.createApp({
116
116
app.directive('pin', {
117
117
mounted(el, binding) {
118
118
el.style.position='fixed'
119
-
// binding.arg is an argument we pass to directive
119
+
// 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">`
137
+
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 ligado. Vamos criar uma propriedade adicional`pinPadding`e ligar 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:
185
+
No exemplo anterior, você pode querer o mesmo comportamento no`mounted`e`updated`, mas não liga para os outros hooks. 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.
197
+
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 válida em javascript.
In 3.0, with fragments support, components can potentially have more than one root nodes. This creates an issue when a custom directive is used on a component with multiple root nodes.
212
+
No 3.0, com o suporte de fragmentos, os componentes podem ter mais de um nó raiz. Isso cria um problema quando a diretiva customizada é utilizada em um componente com múltiplos nós raiz.
213
213
214
-
To explain the details of how custom directives will work on components in 3.0, we need to first understand how custom directives are compiled in 3.0. For a directive like this:
214
+
Para explicar os detalhes de como as diretivas customizadas vão funcionar nos componentes no 3.0, nós precisamos primeiro entender como as diretivas customizadas são compiladas no 3.0. Para uma diretiva assim:
215
215
216
216
```vue-html
217
217
<div v-demo="test"></div>
218
218
```
219
219
220
-
Will roughly compile into this:
220
+
Vai compilar mais ou menos para isso:
221
221
222
222
```js
223
223
constvDemo=resolveDirective('demo')
224
224
225
225
returnwithDirectives(h('div'), [[vDemo, test]])
226
226
```
227
227
228
-
Where`vDemo`will be the directive object written by the user, which contains hooks like`mounted`and`updated`.
228
+
Onde`vDemo`vai ser o objeto de diretiva escrita pelo usuário, que contem os hooks como`mounted`e`updated`.
229
229
230
-
`withDirectives`returns a cloned VNode with the user hooks wrapped and injected as VNode lifecycle hooks (see [Render Function](render-function.html) for more details):
230
+
`withDirectives`retorna um VNode clonada com os hooks do usuário embalados e injetados conforme os hooks do ciclo de vida aplicam ao VNode (Veja [Funções de renderização](render-function.html)) para mais detalhes:
231
231
232
232
```js
233
233
{
234
234
onVnodeMounted(vnode) {
235
-
//call vDemo.mounted(...)
235
+
//vai chamar o vDemo.mounted(...)
236
236
}
237
237
}
238
238
```
239
239
240
-
**As a result, custom directives are fully included as part of a VNode's data. When a custom directive is used on a component, these `onVnodeXXX`hooks are passed down to the component as extraneous props and end up in `this.$attrs`.**
240
+
**Como resultado, a diretiva customizada é incluida como parte dos dados do VNode. Quando a diretiva customizada é usada em um componente, esses hooks do `onVnodeXXX`são passados para o componente como atributos extras e ficam no `this.$attrs`**
241
241
242
-
This also means it's possible to directly hook into an element's lifecycle like this in the template, which can be handy when a custom directive is too involved:
242
+
Isso também significa que é possivel fazer o hook no ciclo de vida do elemento dessa maneira no template, o que pode ser útil quando uma diretiva customizada está envolvida:
243
243
244
244
```vue-html
245
-
<div @vnodeMounted="myHook" />
245
+
<div @vnodeMounted="meuHook" />
246
246
```
247
247
248
-
This is consistent with the [attribute fallthrough behavior](component-attrs.html). So, the rule for custom directives on a component will be the same as other extraneous attributes: it is up to the child component to decide where and whether to apply it. When the child component uses `v-bind="$attrs"`on an inner element, it will apply any custom directives used on it as well.
248
+
Isso é consistente com o [comportamento de fallthrough do atributo](component-attrs.html). Então, a regra para as diretivas customizadas em um componente vai ser a mesma que outros atributos extras: vai do componente filho decidir onde e se vai aplica-lo. Quando o componente filho usa o `v-bind="$attrs"`em um elemento interno, ele vai aplicar em qualquer diretiva customizada utilizada nele também.
0 commit comments