Skip to content

Commit 769ab97

Browse files
committed
Translates custom-directive.md to pt-BR
Closes issue #119
1 parent 8e1c7a2 commit 769ab97

File tree

1 file changed

+71
-71
lines changed

1 file changed

+71
-71
lines changed

src/guide/custom-directive.md

Lines changed: 71 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -1,83 +1,83 @@
1-
# Custom Directives
1+
# Diretivas customizadas (Custom Directives)
22

3-
## Intro
3+
## Introdução
4+
5+
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:
46

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

78
<p class="codepen" data-height="300" data-theme-id="39028" data-default-tab="result" data-user="Vue" data-slug-hash="JjdxaJW" 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="Custom directives: basic example">
8-
<span>See the Pen <a href="https://codepen.io/team/Vue/pen/JjdxaJW">
9-
Custom directives: basic example</a> by Vue (<a href="https://codepen.io/Vue">@Vue</a>)
10-
on <a href="https://codepen.io">CodePen</a>.</span>
9+
<span>Veja o Pen <a href="https://codepen.io/team/Vue/pen/JjdxaJW">
10+
Exemplo básico de diretiva customizada</a> by Vue (<a href="https://codepen.io/Vue">@Vue</a>)
11+
em <a href="https://codepen.io">CodePen</a>.</span>
1112
</p>
1213
<script async src="https://static.codepen.io/assets/embed/ei.js"></script>
1314

14-
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.
1516

16-
Now let's build the directive that accomplishes this:
17+
Agora vamos construir a diretiva que faz isso:
1718

1819
```js
1920
const app = Vue.createApp({})
20-
// Register a global custom directive called `v-focus`
21+
// Registar uma diretiva customizada e global chamada `v-focus`
2122
app.directive('focus', {
22-
// When the bound element is mounted into the DOM...
23+
// Quando o elemento é montado ao DOM
2324
mounted(el) {
24-
// Focus the element
25+
// Foca o elemento
2526
el.focus()
2627
}
2728
})
2829
```
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`:
3131

3232
```js
3333
directives: {
3434
focus: {
35-
// directive definition
35+
// definição da diretiva
3636
mounted(el) {
3737
el.focus()
3838
}
3939
}
4040
}
4141
```
4242

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

4545
```html
4646
<input v-focus />
4747
```
4848

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):
5052

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

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

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

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).
5861
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-
:::
6262

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

65-
- `beforeUnmount`: called before the bound element's parent component is unmounted
65+
- `beforeUnmount`: Executado antes do pai dos elementos ligados sejam desmontados.
6666

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
6868

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)
7070

71-
### Dynamic Directive Arguments
71+
### Argumentos dinâmicos da diretiva
7272

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

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

7777
```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>
78+
<div id="exemplo-argumentos-dinamicos" class="demo">
79+
<p>Role para baixo</p>
80+
<p v-pin="200">Me pregue 200px do topo da página</p>
8181
</div>
8282
```
8383

@@ -87,20 +87,20 @@ const app = Vue.createApp({})
8787
app.directive('pin', {
8888
mounted(el, binding) {
8989
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.
9191
el.style.top = binding.value + 'px'
9292
}
9393
})
9494

95-
app.mount('#dynamic-arguments-example')
95+
app.mount('#exemplo-argumentos-dinamicos')
9696
```
9797

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

100100
```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>
104104
</div>
105105
```
106106

@@ -116,31 +116,31 @@ const app = Vue.createApp({
116116
app.directive('pin', {
117117
mounted(el, binding) {
118118
el.style.position = 'fixed'
119-
// binding.arg is an argument we pass to directive
119+
// binding.arg é um argumento que passamos para a diretiva
120120
const s = binding.arg || 'top'
121121
el.style[s] = binding.value + 'px'
122122
}
123123
})
124124

125-
app.mount('#dynamic-arguments-example')
125+
app.mount('#exemplo-argumentos-dinamicos')
126126
```
127127

128-
Result:
128+
Resultado:
129129

130130
<p class="codepen" data-height="300" data-theme-id="39028" data-default-tab="result" data-user="Vue" data-slug-hash="YzXgGmv" 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="Custom directives: dynamic arguments">
131-
<span>See the Pen <a href="https://codepen.io/team/Vue/pen/YzXgGmv">
132-
Custom directives: dynamic arguments</a> by Vue (<a href="https://codepen.io/Vue">@Vue</a>)
133-
on <a href="https://codepen.io">CodePen</a>.</span>
131+
<span>Veja o Pen <a href="https://codepen.io/team/Vue/pen/YzXgGmv">
132+
Diretivas customizadas: argumentos dinâmicos</a> por Vue (<a href="https://codepen.io/Vue">@Vue</a>)
133+
em <a href="https://codepen.io">CodePen</a>.</span>
134134
</p>
135135
<script async src="https://static.codepen.io/assets/embed/ei.js"></script>
136136

137-
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">`
138138

139139
```vue-html{4}
140-
<div id="dynamicexample">
141-
<h2>Scroll down the page</h2>
140+
<div id="exemplodinamico">
141+
<h2>Role a página para baixo</h2>
142142
<input type="range" min="0" max="500" v-model="pinPadding">
143-
<p v-pin:[direction]="pinPadding">Stick me 200px from the {{ direction }} of the page</p>
143+
<p v-pin:[direction]="pinPadding">Me pregue 200 px da {{ direction }} da página</p>
144144
</div>
145145
```
146146

@@ -155,7 +155,7 @@ const app = Vue.createApp({
155155
})
156156
```
157157

158-
Now let's extend our directive logic to recalculate the distance to pin on component update:
158+
Agora vamos incrementar a lógica da diretiva para recalcular a distância dos elementos pregados quando atualizar o componente:
159159

160160
```js{7-10}
161161
app.directive('pin', {
@@ -171,18 +171,18 @@ app.directive('pin', {
171171
})
172172
```
173173

174-
Result:
174+
Resultado:
175175

176176
<p class="codepen" data-height="300" data-theme-id="39028" data-default-tab="result" data-user="Vue" data-slug-hash="rNOaZpj" 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="Custom directives: dynamic arguments + dynamic binding">
177-
<span>See the Pen <a href="https://codepen.io/team/Vue/pen/rNOaZpj">
178-
Custom directives: dynamic arguments + dynamic binding</a> by Vue (<a href="https://codepen.io/Vue">@Vue</a>)
179-
on <a href="https://codepen.io">CodePen</a>.</span>
177+
<span>Veja o Pen <a href="https://codepen.io/team/Vue/pen/rNOaZpj">
178+
Diretivas customizadas: argumentos dinâmicos + ligamento dinâmico</a> por Vue (<a href="https://codepen.io/Vue">@Vue</a>)
179+
em <a href="https://codepen.io">CodePen</a>.</span>
180180
</p>
181181
<script async src="https://static.codepen.io/assets/embed/ei.js"></script>
182182

183-
## Function Shorthand
183+
## Atalho de função (Function Shorthand)
184184

185-
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:
186186

187187
```js
188188
app.directive('pin', (el, binding) => {
@@ -192,57 +192,57 @@ app.directive('pin', (el, binding) => {
192192
})
193193
```
194194

195-
## Object Literals
195+
## Objetos literais (Object Literals)
196196

197-
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.
198198

199199
```vue-html
200-
<div v-demo="{ color: 'white', text: 'hello!' }"></div>
200+
<div v-demo="{ color: 'white', text: 'ola!!' }"></div>
201201
```
202202

203203
```js
204204
app.directive('demo', (el, binding) => {
205205
console.log(binding.value.color) // => "white"
206-
console.log(binding.value.text) // => "hello!"
206+
console.log(binding.value.text) // => "ola!"
207207
})
208208
```
209209

210-
## Usage on Components
210+
## Utilização nos componentes
211211

212-
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.
213213

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

216216
```vue-html
217217
<div v-demo="test"></div>
218218
```
219219

220-
Will roughly compile into this:
220+
Vai compilar mais ou menos para isso:
221221

222222
```js
223223
const vDemo = resolveDirective('demo')
224224

225225
return withDirectives(h('div'), [[vDemo, test]])
226226
```
227227

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`.
229229

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

232232
```js
233233
{
234234
onVnodeMounted(vnode) {
235-
// call vDemo.mounted(...)
235+
// vai chamar o vDemo.mounted(...)
236236
}
237237
}
238238
```
239239

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`**
241241

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

244244
```vue-html
245-
<div @vnodeMounted="myHook" />
245+
<div @vnodeMounted="meuHook" />
246246
```
247247

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

Comments
 (0)