Skip to content

Translates "guide/instance", "guide/conditional", "guide/component-template-refs" #33

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 14 commits into from
Sep 28, 2020
Merged
14 changes: 7 additions & 7 deletions src/guide/component-template-refs.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
# Template refs
# _refs_ de Template

> This page assumes you've already read the [Components Basics](component-basics.md). Read that first if you are new to components.
> 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.

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

```html
<input ref="input" />
```

This may be useful when you want to, for example, programmatically focus this input on component mount:
Isso pode ser útil quando você deseja, por exemplo, de forma programática, aplicar o _focus_ nesse _input_ na montagem do componente:

```js
const app = Vue.createApp({})
Expand All @@ -28,7 +28,7 @@ app.component('base-input', {
})
```

Also, you can add another `ref` to the component itself and use it to trigger `focusInput` event from the parent component:
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:

```html
<base-input ref="usernameInput"></base-input>
Expand All @@ -39,7 +39,7 @@ this.$refs.usernameInput.focusInput()
```

::: warning
`$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.
`$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.
:::

**See also**: [Using template refs in Composition API](/guide/composition-api-template-refs.html#template-refs)
**Veja também**: [Usando _refs_ de _templates_ na Composition API](/guide/composition-api-template-refs.html#template-refs)
60 changes: 30 additions & 30 deletions src/guide/conditional.md
Original file line number Diff line number Diff line change
@@ -1,50 +1,50 @@
# Conditional Rendering
# Renderização Condicional

## `v-if`

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

```html
<h1 v-if="awesome">Vue is awesome!</h1>
<h1 v-if="awesome">Vue é incrível!</h1>
```

It is also possible to add an "else block" with `v-else`:
Também é possível adicionar um "bloco _else_" usando `v-else`:

```html
<h1 v-if="awesome">Vue is awesome!</h1>
<h1 v-else>Oh no 😢</h1>
<h1 v-if="awesome">Vue é incrível!</h1>
<h1 v-else>Oh não 😢</h1>
```

### Conditional Groups with `v-if` on `<template>`
### Grupos Condicionais com `v-if` em `<template>`

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

```html
<template v-if="ok">
<h1>Title</h1>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<h1>Título</h1>
<p>Parágrafo 1</p>
<p>Parágrafo 2</p>
</template>
```

### `v-else`

You can use the `v-else` directive to indicate an "else block" for `v-if`:
É possível utilizar a diretiva `v-else` para indicar um "bloco _else_" para `v-if`:

```html
<div v-if="Math.random() > 0.5">
Now you see me
Agora você me vê
</div>
<div v-else>
Now you don't
Agora você não me vê
</div>
```

A `v-else` element must immediately follow a `v-if` or a `v-else-if` element - otherwise it will not be recognized.
Um elemento `v-else` deve vir imediatamente após um elemento `v-if` ou `v-else-if`, caso contrário não será reconhecido.

### `v-else-if`

The `v-else-if`, as the name suggests, serves as an "else if block" for `v-if`. It can also be chained multiple times:
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:

```html
<div v-if="type === 'A'">
Expand All @@ -57,38 +57,38 @@ The `v-else-if`, as the name suggests, serves as an "else if block" for `v-if`.
C
</div>
<div v-else>
Not A/B/C
Não A, B ou C
</div>
```

Similar to `v-else`, a `v-else-if` element must immediately follow a `v-if` or a `v-else-if` element.
Similar ao `v-else`, um `v-else-if` deve vir imediatamente após um elemento `v-if` ou um elemento `v-else-if`.

## `v-show`

Another option for conditionally displaying an element is the `v-show` directive. The usage is largely the same:
Outra opção para exibir condicionalmente um elemento é a diretiva `v-show`. A utilização é basicamente a mesma:

```html
<h1 v-show="ok">Hello!</h1>
<h1 v-show="ok">Olá!</h1>
```

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

`v-show` doesn't support the `<template>` element, nor does it work with `v-else`.
`v-show` não suporta o elemento `<template>`, nem funciona com `v-else`.

## `v-if` vs `v-show`

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

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

In comparison, `v-show` is much simpler - the element is always rendered regardless of initial condition, with CSS-based toggling.
Em comparação, `v-show` é mais simples - o elemento sempre será renderizado independentemente da condição inicial, com alternância baseada em CSS.

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

## `v-if` with `v-for`
## `v-if` com `v-for`

::: tip Note
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.
::: tip Nota
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.
:::

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.
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.
74 changes: 37 additions & 37 deletions src/guide/instance.md
Original file line number Diff line number Diff line change
@@ -1,27 +1,27 @@
# The Application Instance
# A Instância da Aplicação

## Creating an Instance
## Criando uma instância

Every Vue application starts by creating a new **application instance** with the `createApp` function:
Toda aplicação Vue começa com a criação de uma nova **instância** com a função `createApp`:

```js
Vue.createApp(/* options */)
Vue.createApp(/* opções */)
```

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

```js
Vue.createApp(/* options */).mount('#app')
Vue.createApp(/* opções */).mount('#app')
```

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

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

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

```
Root Instance
Instância Raiz
└─ TodoList
├─ TodoItem
│ ├─ DeleteTodoButton
Expand All @@ -31,40 +31,40 @@ Root Instance
└─ TodoListStatistics
```

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

## Data and Methods
## Dados e Métodos

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

```js
// Our data object
// Nosso objeto de dados
const data = { a: 1 }

// The object is added to the root instance
// O objeto é adicionado à instância raiz
const vm = Vue.createApp({
data() {
return data
}
}).mount('#app')

// Getting the property on the instance
// returns the one from the original data
// Acessar a propriedade na instância
// retorna aquilo que está no dado original
vm.a === data.a // => true

// Setting the property on the instance
// also affects the original data
// Atribuir à propriedade na instância
// também afeta o dado original
vm.a = 2
data.a // => 2
```

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

```js
vm.b = 'hi'
```

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

```js
data() {
Expand All @@ -78,7 +78,7 @@ data() {
}
```

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

```js
const obj = {
Expand All @@ -97,12 +97,12 @@ const vm = Vue.createApp({
```html
<div id="app">
<p>{{ foo }}</p>
<!-- this will no longer update `foo`! -->
<button v-on:click="foo = 'baz'">Change it</button>
<!-- não irá atualizar mais o `foo`! -->
<button v-on:click="foo = 'baz'">Alterar</button>
</div>
```

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

```js
const vm = Vue.createApp({
Expand All @@ -116,13 +116,13 @@ const vm = Vue.createApp({
vm.$data.a // => 1
```

In the future, you can consult the [API reference](../api/instance-properties.html) for a full list of instance properties and methods.
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.

## Instance Lifecycle Hooks
## Gatilhos de Ciclo de Vida da Instância

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

For example, the [created](../api/options-lifecycle-hooks.html#created) hook can be used to run code after an instance is created:
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:

```js
Vue.createApp({
Expand All @@ -132,20 +132,20 @@ Vue.createApp({
}
},
created() {
// `this` points to the vm instance
console.log('a is: ' + this.a) // => "a is: 1"
// `this` aponta para a instância
console.log('a é: ' + this.a) // => "a é: 1"
}
})
```

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

::: tip
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`.
::: tip Nota
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`.
:::

## Lifecycle Diagram
## Diagrama do Ciclo de Vida

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

<img src="/images/lifecycle.png" width="840" height="auto" style="margin: 0px auto; display: block; max-width: 100%;" loading="lazy" alt="Instance lifecycle hooks">
<img src="/images/lifecycle.png" width="840" height="auto" style="margin: 0px auto; display: block; max-width: 100%;" loading="lazy" alt="Diagrama do ciclo de vida">