Skip to content

Commit 56232fd

Browse files
authored
Merge pull request #176 from rhiroshi/patch-1
Traduz custom-directive.md para pt-BR
2 parents 341ce93 + 682a2b4 commit 56232fd

File tree

1 file changed

+55
-55
lines changed

1 file changed

+55
-55
lines changed

src/guide/custom-directive.md

Lines changed: 55 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -1,80 +1,80 @@
1-
# Custom Directives
1+
# Diretivas Customizadas
22

3-
## Intro
3+
## Introdução
44

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

7-
<common-codepen-snippet title="Custom directives: basic example" slug="JjdxaJW" :preview="false" />
7+
<common-codepen-snippet title="Diretivas customizadas: exemplo básico" slug="JjdxaJW" :preview="false" />
88

9-
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.
1010

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

1313
```js
1414
const app = Vue.createApp({})
15-
// Register a global custom directive called `v-focus`
15+
// Registra uma diretiva customizada global chamada `v-focus`
1616
app.directive('focus', {
17-
// When the bound element is mounted into the DOM...
17+
// Quando o elemento vinculado é inserido no DOM
1818
mounted(el) {
19-
// Focus the element
19+
// Foca o elemento
2020
el.focus()
2121
}
2222
})
2323
```
2424

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

2727
```js
2828
directives: {
2929
focus: {
30-
// directive definition
30+
// definição da diretiva
3131
mounted(el) {
3232
el.focus()
3333
}
3434
}
3535
}
3636
```
3737

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

4040
```html
4141
<input v-focus />
4242
```
4343

44-
## Hook Functions
44+
## Funções de Gatilhos (Hook Functions)
4545

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

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

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

52-
- `mounted`: called when the bound element's parent component is mounted.
52+
- `mounted`: Executa quando o componente pai do elemento ligado é montado.
5353

54-
- `beforeUpdate`: called before the containing component's VNode is updated
54+
- `beforeUpdate`: Executa antes que o VNode contido no componente seja atualizado.
5555

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).
5858
:::
5959

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

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

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
6565

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

68-
### Dynamic Directive Arguments
68+
### Argumentos Dinâmicos de Diretiva
6969

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

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

7474
```vue-html
7575
<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>
7878
</div>
7979
```
8080

@@ -84,20 +84,20 @@ const app = Vue.createApp({})
8484
app.directive('pin', {
8585
mounted(el, binding) {
8686
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.
8888
el.style.top = binding.value + 'px'
8989
}
9090
})
9191

9292
app.mount('#dynamic-arguments-example')
9393
```
9494

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

9797
```vue-html
9898
<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>
101101
</div>
102102
```
103103

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

122-
app.mount('#dynamic-arguments-example')
122+
app.mount('#exemplo-argumentos-dinamicos')
123123
```
124124

125-
Result:
125+
Resultado:
126126

127-
<common-codepen-snippet title="Custom directives: dynamic arguments" slug="YzXgGmv" :preview="false" />
127+
<common-codepen-snippet title="Diretivas customizadas: argumentos dinâmicos" slug="YzXgGmv" :preview="false" />
128128

129-
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">`
130130

131131
```vue-html{4}
132132
<div id="dynamicexample">
133-
<h2>Scroll down the page</h2>
133+
<h2>Role a página para baixo</h2>
134134
<input type="range" min="0" max="500" v-model="pinPadding">
135-
<p v-pin:[direction]="pinPadding">Stick me {{ pinPadding + 'px' }} from the {{ direction || 'top' }} of the page</p>
135+
<p v-pin:[direction]="pinPadding">Me pregue {{ pinPadding + 'px' }} da {{ direction || 'top' }} da página</p>
136136
</div>
137137
```
138138

@@ -147,7 +147,7 @@ const app = Vue.createApp({
147147
})
148148
```
149149

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

152152
```js{7-10}
153153
app.directive('pin', {
@@ -163,13 +163,13 @@ app.directive('pin', {
163163
})
164164
```
165165

166-
Result:
166+
Resultado:
167167

168-
<common-codepen-snippet title="Custom directives: dynamic arguments + dynamic binding" slug="rNOaZpj" :preview="false" />
168+
<common-codepen-snippet title="Diretivas customizadas: argumentos dinâmicos + vínculo dinâmico" slug="rNOaZpj" :preview="false" />
169169

170-
## Function Shorthand
170+
## Atalho da Função (Function Shorthand)
171171

172-
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:
173173

174174
```js
175175
app.directive('pin', (el, binding) => {
@@ -179,24 +179,24 @@ app.directive('pin', (el, binding) => {
179179
})
180180
```
181181

182-
## Object Literals
182+
## Objetos Literais (Object Literals)
183183

184-
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.
185185

186186
```vue-html
187-
<div v-demo="{ color: 'white', text: 'hello!' }"></div>
187+
<div v-demo="{ color: 'white', text: 'olá!!' }"></div>
188188
```
189189

190190
```js
191191
app.directive('demo', (el, binding) => {
192192
console.log(binding.value.color) // => "white"
193-
console.log(binding.value.text) // => "hello!"
193+
console.log(binding.value.text) // => "olá!"
194194
})
195195
```
196196

197-
## Usage on Components
197+
## Uso em Componentes
198198

199-
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).
200200

201201
```vue-html
202202
<my-component v-demo="test"></my-component>
@@ -205,13 +205,13 @@ When used on components, custom directive will always apply to component's root
205205
```js
206206
app.component('my-component', {
207207
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>
210210
</div>
211211
`
212212
})
213213
```
214214

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"`.
216216

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

Comments
 (0)