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
Copy file name to clipboardExpand all lines: src/guide/component-template-refs.md
+7-7Lines changed: 7 additions & 7 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,14 +1,14 @@
1
-
# Template refs
1
+
# _refs_ de Template
2
2
3
-
> This page assumes you've already read the [Components Basics](component-basics.md). Read that first if you are new to components.
3
+
> Esta página assume que você já leu o [Básico de Componentes](component-basics.md). Leia lá primeiro se você for novo em componentes.
4
4
5
-
Despite the existence of props and events, sometimes you might still need to directly access a child component in JavaScript. To achieve this you can assign a reference ID to the child component or HTML element using the`ref` attribute. For example:
5
+
Apesar da existência de propriedades e eventos, às vezes você ainda pode precisar acessar diretamente um componente filho em JavaScript. Para isso, você pode atribuir um ID de referência ao componente filho ou elemento HTML usando o atributo`ref`. Por exemplo:
6
6
7
7
```html
8
8
<inputref="input" />
9
9
```
10
10
11
-
This may be useful when you want to, for example, programmatically focus this input on component mount:
11
+
Isso pode ser útil quando você deseja, por exemplo, de forma programática, aplicar o _focus_ nesse _input_ na montagem do componente:
12
12
13
13
```js
14
14
constapp=Vue.createApp({})
@@ -28,7 +28,7 @@ app.component('base-input', {
28
28
})
29
29
```
30
30
31
-
Also, you can add another`ref`to the component itself and use it to trigger`focusInput`event from the parent component:
31
+
Além disso, você pode adicionar outro`ref`ao próprio componente e usá-lo para acionar o evento`focusInput`a partir do componente pai:
`$refs`are only populated after the component has been rendered. It is only meant as an escape hatch for direct child manipulation - you should avoid accessing`$refs`from within templates or computed properties.
42
+
`$refs`é preenchido apenas após o componente ter sido renderizado. Isso serve apenas como uma saída de emergência para a manipulação direta de elementos filhos - você deve evitar acessar`$refs`de dentro de _templates_ ou dados computados.
43
43
:::
44
44
45
-
**See also**: [Using template refs in Composition API](/guide/composition-api-template-refs.html#template-refs)
45
+
**Veja também**: [Usando _refs_ de _templates_ na Composition API](/guide/composition-api-template-refs.html#template-refs)
The directive`v-if`is used to conditionally render a block. The block will only be rendered if the directive's expression returns a truthy value.
5
+
A diretiva`v-if`é usada para renderizar condicionalmente um bloco. O bloco só será renderizado se a expressão na diretiva retornar um valor verdadeiro.
6
6
7
7
```html
8
-
<h1v-if="awesome">Vue is awesome!</h1>
8
+
<h1v-if="awesome">Vue é incrível!</h1>
9
9
```
10
10
11
-
It is also possible to add an "else block" with`v-else`:
11
+
Também é possível adicionar um "bloco _else_" usando`v-else`:
12
12
13
13
```html
14
-
<h1v-if="awesome">Vue is awesome!</h1>
15
-
<h1v-else>Oh no 😢</h1>
14
+
<h1v-if="awesome">Vue é incrível!</h1>
15
+
<h1v-else>Oh não 😢</h1>
16
16
```
17
17
18
-
### Conditional Groups with`v-if`on`<template>`
18
+
### Grupos Condicionais com`v-if`em`<template>`
19
19
20
-
Because`v-if`is a directive, it has to be attached to a single element. But what if we want to toggle more than one element? In this case we can use `v-if`on a `<template>` element, which serves as an invisible wrapper. The final rendered result will not include the `<template>` element.
20
+
Como`v-if`é uma diretiva, então deve ser anexado à um único elemento. E se quisermos alternar mais de um elemento? Nesse caso podemos usar `v-if`em um elemento `<template>`, que serve como um _wrapper_ invisível. O resultado final renderizado não incluirá o elemento `<template>`.
21
21
22
22
```html
23
23
<templatev-if="ok">
24
-
<h1>Title</h1>
25
-
<p>Paragraph 1</p>
26
-
<p>Paragraph 2</p>
24
+
<h1>Título</h1>
25
+
<p>Parágrafo 1</p>
26
+
<p>Parágrafo 2</p>
27
27
</template>
28
28
```
29
29
30
30
### `v-else`
31
31
32
-
You can use the `v-else`directive to indicate an "else block" for`v-if`:
32
+
É possível utilizar a diretiva `v-else`para indicar um "bloco _else_" para`v-if`:
33
33
34
34
```html
35
35
<divv-if="Math.random() > 0.5">
36
-
Now you see me
36
+
Agora você me vê
37
37
</div>
38
38
<divv-else>
39
-
Now you don't
39
+
Agora você não me vê
40
40
</div>
41
41
```
42
42
43
-
A `v-else`element must immediately follow a `v-if`or a `v-else-if` element - otherwise it will not be recognized.
43
+
Um elemento `v-else`deve vir imediatamente após um elemento `v-if`ou `v-else-if`, caso contrário não será reconhecido.
44
44
45
45
### `v-else-if`
46
46
47
-
The`v-else-if`, as the name suggests, serves as an "else if block" for`v-if`. It can also be chained multiple times:
47
+
O`v-else-if`, como o nome sugere, serve como um "bloco _else if_" ao`v-if`. Ele pode, inclusive, ser encadeado várias vezes:
48
48
49
49
```html
50
50
<divv-if="type === 'A'">
@@ -57,38 +57,38 @@ The `v-else-if`, as the name suggests, serves as an "else if block" for `v-if`.
57
57
C
58
58
</div>
59
59
<divv-else>
60
-
Not A/B/C
60
+
Não A, B ou C
61
61
</div>
62
62
```
63
63
64
-
Similar to`v-else`, a`v-else-if`element must immediately follow a `v-if`or a `v-else-if` element.
64
+
Similar ao`v-else`, um`v-else-if`deve vir imediatamente após um elemento `v-if`ou um elemento `v-else-if`.
65
65
66
66
## `v-show`
67
67
68
-
Another option for conditionally displaying an element is the `v-show` directive. The usage is largely the same:
68
+
Outra opção para exibir condicionalmente um elemento é a diretiva `v-show`. A utilização é basicamente a mesma:
69
69
70
70
```html
71
-
<h1v-show="ok">Hello!</h1>
71
+
<h1v-show="ok">Olá!</h1>
72
72
```
73
73
74
-
The difference is that an element with`v-show`will always be rendered and remain in the DOM; `v-show`only toggles the `display`CSS property of the element.
74
+
A diferença é que um elemento com`v-show`sempre será renderizado e permanecerá no DOM; `v-show`simplesmente alterna a propriedade CSS `display`do elemento.
75
75
76
-
`v-show`doesn't support the `<template>` element, nor does it work with`v-else`.
76
+
`v-show`não suporta o elemento `<template>`, nem funciona com`v-else`.
77
77
78
78
## `v-if` vs `v-show`
79
79
80
-
`v-if`is "real" conditional rendering because it ensures that event listeners and child components inside the conditional block are properly destroyed and re-created during toggles.
80
+
`v-if`é a renderização condicional "real", pois garante que eventos e componentes filhos dentro do bloco condicional sejam devidamente destruídos e recriados durante a alternância.
81
81
82
-
`v-if`is also**lazy**: if the condition is false on initial render, it will not do anything - the conditional block won't be rendered until the condition becomes true for the first time.
82
+
`v-if`também é**preguiçoso**: se a condição for _false_ na renderização inicial, nada será feito - o bloco condicional não será renderizado até que a condição se torne _true_ pela primeira vez.
83
83
84
-
In comparison, `v-show`is much simpler - the element is always rendered regardless of initial condition, with CSS-based toggling.
84
+
Em comparação, `v-show`é mais simples - o elemento sempre será renderizado independentemente da condição inicial, com alternância baseada em CSS.
85
85
86
-
Generally speaking, `v-if`has higher toggle costs while `v-show`has higher initial render costs. So prefer`v-show`if you need to toggle something very often, and prefer`v-if`if the condition is unlikely to change at runtime.
86
+
De modo geral, `v-if`tem custo maior nas alternâncias de renderização, enquanto que `v-show`tem custo maior na renderização inicial. Então prefira`v-show`se precisar alternar a visibilidade de algo com muita frequência, e prefira`v-if`se a condição não for se alterar muito durante _runtime_.
87
87
88
-
## `v-if`with`v-for`
88
+
## `v-if`com`v-for`
89
89
90
-
::: tip Note
91
-
Using`v-if`and`v-for`together is **not recommended**. See the [style guide](../style-guide/#avoid-v-if-with-v-for-essential)for further information.
90
+
::: tip Nota
91
+
Usar`v-if`e`v-for`juntos **não é recomendado**. Veja o [guia de estilos](../style-guide/#avoid-v-if-with-v-for-essential)para mais informações.
92
92
:::
93
93
94
-
When used together with `v-if`, `v-for`has a higher priority than`v-if`. See the [list rendering guide](list#v-for-with-v-if)for details.
94
+
Quando usado em conjunto com `v-if`, `v-for`possui maior prioridade do que`v-if`. Veja o [guia de renderização de listas](list#v-for-with-v-if)para mais detalhes.
Every Vue application starts by creating a new **application instance**with the `createApp` function:
5
+
Toda aplicação Vue começa com a criação de uma nova **instância**com a função `createApp`:
6
6
7
7
```js
8
-
Vue.createApp(/*options*/)
8
+
Vue.createApp(/*opções*/)
9
9
```
10
10
11
-
After the instance is created, we can _mount_ it, passing a container to`mount` method. For example, if we want to mount a Vue application on `<div id="app"></div>`, we should pass`#app`:
11
+
Após a instância ser criada, podemos _montá-la_, passando um contêiner para o método`mount`. Por exemplo, se quisermos montar um aplicativo Vue em `<div id="app"></div>`, devemos passar`#app`:
12
12
13
13
```js
14
-
Vue.createApp(/*options*/).mount('#app')
14
+
Vue.createApp(/*opções*/).mount('#app')
15
15
```
16
16
17
-
Although not strictly associated with the [MVVM pattern](https://en.wikipedia.org/wiki/Model_View_ViewModel), Vue's design was partly inspired by it. As a convention, we often use the variable`vm` (short for ViewModel) to refer to our instance.
17
+
Embora não seja estritamente associado com o [padrão MVVM](https://en.wikipedia.org/wiki/Model_View_ViewModel), o _design_ do Vue foi parcialmente inspirado por ele. Por convenção, muitas vezes usamos a variável`vm` (abreviação de _ViewModel_) para se referir à instância Vue.
18
18
19
-
When you create an instance, you pass in an**options object**. The majority of this guide describes how you can use these options to create your desired behavior. For reference, you can also browse the full list of options in the [API reference](../api/options-data.html).
19
+
Quando você cria uma instância Vue, é necessário passar um**objeto de opções**. A maior parte deste guia descreve como você pode utilizar estas opções para criar os comportamentos desejados. Para referência, você também pode navegar pela lista completa de opções na [documentação da API](../api/options-data.html).
20
20
21
-
A Vue application consists of a **root instance**created with`createApp`, optionally organized into a tree of nested, reusable components. For example, a `todo` app's component tree might look like this:
21
+
Uma aplicação Vue consiste em uma **instância raiz**criada com`createApp`, opcionalmente organizada em uma árvore de componentes reutilizáveis aninhados. Por exemplo, um aplicativo de tarefas a realizar (do tipo _todo list_) poderia ter uma árvore de componentes como esta:
22
22
23
23
```
24
-
Root Instance
24
+
Instância Raiz
25
25
└─ TodoList
26
26
├─ TodoItem
27
27
│ ├─ DeleteTodoButton
@@ -31,40 +31,40 @@ Root Instance
31
31
└─ TodoListStatistics
32
32
```
33
33
34
-
We'll talk about [the component system](component-basics.html)in detail later. For now, just know that all Vue components are also instances, and so accept the same options object.
34
+
Falaremos sobre [o sistema de componentes](component-basics.html)em detalhes futuramente. Por enquanto, apenas saiba que todos os componentes Vue também são instâncias, e assim aceitam o mesmo objeto de opções.
35
35
36
-
## Data and Methods
36
+
## Dados e Métodos
37
37
38
-
When an instance is created, it adds all the properties found in its`data`to [Vue's **reactivity system**](reactivity.html). When the values of those properties change, the view will "react", updating to match the new values.
38
+
Quando uma instância é criada, ela adiciona todas as propriedades encontradas no objeto`data`ao [**sistema de reatividade** do Vue](reactivity.html). Quando os valores dessas propriedades mudam, a camada visual (em inglês, _view_) "reage", atualizando-se para corresponder aos novos valores.
39
39
40
40
```js
41
-
//Our data object
41
+
//Nosso objeto de dados
42
42
constdata= { a:1 }
43
43
44
-
//The object is added to the root instance
44
+
//O objeto é adicionado à instância raiz
45
45
constvm=Vue.createApp({
46
46
data() {
47
47
return data
48
48
}
49
49
}).mount('#app')
50
50
51
-
//Getting the property on the instance
52
-
//returns the one from the original data
51
+
//Acessar a propriedade na instância
52
+
//retorna aquilo que está no dado original
53
53
vm.a===data.a// => true
54
54
55
-
//Setting the property on the instance
56
-
//also affects the original data
55
+
//Atribuir à propriedade na instância
56
+
//também afeta o dado original
57
57
vm.a=2
58
58
data.a// => 2
59
59
```
60
60
61
-
When this data changes, the view will re-render. It should be noted that properties in `data`are only**reactive**if they existed when the instance was created. That means if you add a new property, like:
61
+
Quando este dado for modificado, a camada visual irá "re-renderizar". Deve-se observar que as propriedades em `data`só são**reativas**se elas já existiam quando a instância foi criada. Isso significa que se você adicionar uma nova propriedade, como:
62
62
63
63
```js
64
64
vm.b='hi'
65
65
```
66
66
67
-
Then changes to `b`will not trigger any view updates. If you know you'll need a property later, but it starts out empty or non-existent, you'll need to set some initial value. For example:
67
+
Então as mudanças em `b`não irão disparar qualquer atualização na interface. Se você sabe que precisará de uma propriedade no futuro, mas ela inicia vazia ou não existente, você precisará atribuir algum valor inicial. Por exemplo:
68
68
69
69
```js
70
70
data() {
@@ -78,7 +78,7 @@ data() {
78
78
}
79
79
```
80
80
81
-
The only exception to this being the use of `Object.freeze()`, which prevents existing properties from being changed, which also means the reactivity system can't _track_ changes.
81
+
A única exceção é quanto ao uso do `Object.freeze()`, que previne propriedades existentes de serem modificadas, o que também significa que o sistema de reatividade não pode _rastrear_ mudanças.
In addition to data properties, instances expose a number of useful instance properties and methods. These are prefixed with`$`to differentiate them from user-defined properties. For example:
105
+
Em adição às propriedades de dados, instâncias expõem uma quantidade relevante de propriedades e métodos. Estes são prefixados com`$`para diferenciá-los das propriedades definidas pelo usuário. Por exemplo:
106
106
107
107
```js
108
108
constvm=Vue.createApp({
@@ -116,13 +116,13 @@ const vm = Vue.createApp({
116
116
vm.$data.a// => 1
117
117
```
118
118
119
-
In the future, you can consult the [API reference](../api/instance-properties.html)for a full list of instance properties and methods.
119
+
No futuro, você pode consultar a [documentação da API](../api/instance-properties.html)para a lista completa de propriedades e métodos da instância.
120
120
121
-
## Instance Lifecycle Hooks
121
+
## Gatilhos de Ciclo de Vida da Instância
122
122
123
-
Each instance goes through a series of initialization steps when it's created - for example, it needs to set up data observation, compile the template, mount the instance to the DOM, and update the DOM when data changes. Along the way, it also runs functions called **lifecycle hooks**, giving users the opportunity to add their own code at specific stages.
123
+
Cada instância Vue passa por uma série de etapas em sua inicialização - por exemplo, é necessário configurar a observação de dados, compilar o _template_, montar a instância no DOM, e atualizar o DOM quando os dados forem alterados. Ao longo do caminho, também ocorre a invocação de algumas funções chamadas de **gatilhos de ciclo de vida** (em inglês, _lifecycle hooks_), oferecendo a oportunidade de executar lógicas personalizadas em etapas específicas.
124
124
125
-
For example, the [created](../api/options-lifecycle-hooks.html#created)hook can be used to run code after an instance is created:
125
+
Por exemplo, o gatilho [`created`](../api/options-lifecycle-hooks.html#created)pode ser utilizado para executar código logo após a instância ser criada:
126
126
127
127
```js
128
128
Vue.createApp({
@@ -132,20 +132,20 @@ Vue.createApp({
132
132
}
133
133
},
134
134
created() {
135
-
// `this` points to the vm instance
136
-
console.log('a is: '+this.a) // => "a is: 1"
135
+
// `this` aponta para a instância
136
+
console.log('a é: '+this.a) // => "a é: 1"
137
137
}
138
138
})
139
139
```
140
140
141
-
There are also other hooks which will be called at different stages of the instance's lifecycle, such as [mounted](../api/options-lifecycle-hooks.html#mounted), [updated](../api/options-lifecycle-hooks.html#updated), and [unmounted](../api/options-lifecycle-hooks.html#unmounted). All lifecycle hooks are called with their `this`context pointing to the current active instance invoking it.
141
+
Existem também outros gatilhos que serão chamados em diferentes etapas do ciclo de vida da instância, como [`mounted`](../api/options-lifecycle-hooks.html#mounted), [`updated`](../api/options-lifecycle-hooks.html#updated), e [`unmounted`](../api/options-lifecycle-hooks.html#unmounted). Todos os gatilhos de ciclo de vida são executados com seu contexto `this`apontando para a atual instância ativa que o invoca.
142
142
143
-
::: tip
144
-
Don't use [arrow functions](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions)on an options property or callback, such as`created: () => console.log(this.a)`or`vm.$watch('a', newValue => this.myMethod())`. Since an arrow function doesn't have a`this`,`this`will be treated as any other variable and lexically looked up through parent scopes until found, often resulting in errors such as `Uncaught TypeError: Cannot read property of undefined`or`Uncaught TypeError: this.myMethod is not a function`.
143
+
::: tip Nota
144
+
Não utilize [_arrow functions_](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Functions/Arrow_functions)em propriedades de opções ou _callback_, como em`created: () => console.log(this.a)`ou`vm.$watch('a', newValue => this.myMethod())`. Como as _arrow functions_ não possuem um`this`,`this`será tratado como qualquer outra variável e lexicamente pesquisada através de escopos parentais até ser encontrada, frequentemente resultando em erros como `Uncaught TypeError: Cannot read property of undefined`ou`Uncaught TypeError: this.myMethod is not a function`.
145
145
:::
146
146
147
-
## Lifecycle Diagram
147
+
## Diagrama do Ciclo de Vida
148
148
149
-
Below is a diagram for the instance lifecycle. You don't need to fully understand everything going on right now, but as you learn and build more, it will be a useful reference.
149
+
Abaixo está um diagrama para o ciclo de vida da instância. Neste momento você não precisa entender completamente tudo o que está acontecendo, mas conforme você for aprendendo e construindo mais coisas, este diagrama se tornará uma referência útil.
<imgsrc="/images/lifecycle.png"width="840"height="auto"style="margin: 0pxauto; display: block; max-width: 100%;"loading="lazy"alt="Diagrama do ciclo de vida">
0 commit comments