Skip to content

Commit 7e2cc2d

Browse files
authored
Merge pull request #36 from cacauisadog/master
translate guide/template-syntax.md to pt-br, closes #4
2 parents 6545084 + f9445ac commit 7e2cc2d

File tree

1 file changed

+75
-75
lines changed

1 file changed

+75
-75
lines changed

src/guide/template-syntax.md

Lines changed: 75 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -1,209 +1,209 @@
1-
# Template Syntax
1+
# Sintaxe de Templates
22

3-
Vue.js uses an HTML-based template syntax that allows you to declaratively bind the rendered DOM to the underlying application instance's data. All Vue.js templates are valid HTML that can be parsed by spec-compliant browsers and HTML parsers.
3+
O Vue.js utiliza uma sintaxe de _templates_ baseada em HTML que permite que você vincule declarativamente o DOM renderizado aos dados da aplicação da instância que existe por baixo. Todos os _templates_ do Vue.js são compostos por HTML válido que pode ser interpretado por navegadores compatíveis com as especificações e também por _parsers_ de HTML.
44

5-
Under the hood, Vue compiles the templates into Virtual DOM render functions. Combined with the reactivity system, Vue is able to intelligently figure out the minimal number of components to re-render and apply the minimal amount of DOM manipulations when the app state changes.
5+
Internamente, o Vue compila os _templates_ em funções de renderização do Virtual DOM. Combinado com o sistema de reatividade, Vue é capaz de identificar de forma inteligente a menor quantidade possível de componentes a serem “re-renderizados” e aplica o mínimo possível de manipulações do DOM quando o estado da aplicação muda.
66

7-
If you are familiar with Virtual DOM concepts and prefer the raw power of JavaScript, you can also [directly write render functions](render-function.html) instead of templates, with optional JSX support.
7+
Se você é familiarizado com os conceitos de Virtual DOM e prefere o poder do JavaScript puro, você também pode escrever [funções de renderização](render-function.html) ao invés de _templates_, com suporte opcional ao JSX.
88

9-
## Interpolations
9+
## Interpolações
1010

11-
### Text
11+
### Texto
1212

13-
The most basic form of data binding is text interpolation using the "Mustache" syntax (double curly braces):
13+
A forma mais básica de vinculação de dados é interpolação de texto utilizando a sintaxe _"Mustache"_ (chaves duplas):
1414

1515
```html
16-
<span>Message: {{ msg }}</span>
16+
<span>Mensagem: {{ msg }}</span>
1717
```
1818

19-
The mustache tag will be replaced with the value of the `msg` property on the corresponding data object. It will also be updated whenever the data object's `msg` property changes.
19+
As chaves duplas serão substituídas pelo valor da propriedade `msg` do objeto de dados correspondente. Esse texto também será atualizado sempre que a propriedade `msg` for modificada.
2020

21-
You can also perform one-time interpolations that do not update on data change by using the [v-once directive](../api/directives.html#v-once), but keep in mind this will also affect any other bindings on the same node:
21+
Você também pode realizar interpolações únicas que não são atualizadas quando os dados mudam através da [diretiva `v-once`](../api/directives.html#v-once), mas mantenha em mente que isso afetará qualquer vinculação realizada no mesmo nó:
2222

2323
```html
24-
<span v-once>This will never change: {{ msg }}</span>
24+
<span v-once>Este valor nunca será modificado: {{ msg }}</span>
2525
```
2626

27-
### Raw HTML
27+
### HTML Puro
2828

29-
The double mustaches interprets the data as plain text, not HTML. In order to output real HTML, you will need to use the [`v-html` directive](../api/directives.html#v-html):
29+
As chaves duplas interpretam os dados como texto simples, não HTML. Para que você exiba HTML, utilize a [diretiva `v-html`](../api/directives.html#v-html):
3030

3131
```html
32-
<p>Using mustaches: {{ rawHtml }}</p>
33-
<p>Using v-html directive: <span v-html="rawHtml"></span></p>
32+
<p>Interpolação textual: {{ rawHtml }}</p>
33+
<p>Diretiva v-html: <span v-html="rawHtml"></span></p>
3434
```
3535

36-
<p class="codepen" data-height="300" data-theme-id="39028" data-default-tab="result" data-user="Vue" data-slug-hash="yLNEJJM" 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="Rendering v-html">
37-
<span>See the Pen <a href="https://codepen.io/team/Vue/pen/yLNEJJM">
38-
Rendering v-html</a> by Vue (<a href="https://codepen.io/Vue">@Vue</a>)
39-
on <a href="https://codepen.io">CodePen</a>.</span>
36+
<p class="codepen" data-height="300" data-theme-id="39028" data-default-tab="result" data-user="Vue" data-slug-hash="yLNEJJM" 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="Renderizando v-html">
37+
<span>Veja o exemplo <a href="https://codepen.io/vuejs-br/pen/MWyZLyQ">
38+
Renderizando v-html</a> por Vue.js Brasil (<a href="https://codepen.io/vuejs-br">@vuejs-br</a>)
39+
no <a href="https://codepen.io">CodePen</a>.</span>
4040
</p>
4141
<script async src="https://static.codepen.io/assets/embed/ei.js"></script>
4242

43-
The contents of the `span` will be replaced with the value of the `rawHtml` property, interpreted as plain HTML - data bindings are ignored. Note that you cannot use `v-html` to compose template partials, because Vue is not a string-based templating engine. Instead, components are preferred as the fundamental unit for UI reuse and composition.
43+
Os conteúdos do `span` serão substituídos pelo valor da propriedade `rawHtml`, interpretada como HTML puro - vínculos de dados são ignorados. Note que você não pode utilizar a diretiva `v-html` para compor templates parciais, porque o Vue não é uma _engine_ de _templates_ baseada em Strings. Ao invés disso, componentes são a maneira indicada como unidade fundamental de composição e reutilização de elementos de interface.
4444

4545
::: tip
46-
Dynamically rendering arbitrary HTML on your website can be very dangerous because it can easily lead to [XSS vulnerabilities](https://en.wikipedia.org/wiki/Cross-site_scripting). Only use HTML interpolation on trusted content and **never** on user-provided content
46+
Renderizar dinamicamente HTML arbitrário no seu _site_ pode ser muito perigoso, pois pode facilmente levar a [ataques XSS](https://pt.wikipedia.org/wiki/Cross-site_scripting). Utilize a interpolação de HTML apenas em conteúdos que você confia e **nunca** em conteúdos enviados por usuários.
4747
:::
4848

49-
### Attributes
49+
### Atributos
5050

51-
Mustaches cannot be used inside HTML attributes. Instead, use a [`v-bind` directive](../api/#v-bind):
51+
Chaves duplas não podem ser usadas em atributos HTML. Para isso, utilize a [diretiva v-bind]((../api/#v-bind)):
5252

5353
```html
5454
<div v-bind:id="dynamicId"></div>
5555
```
5656

57-
In the case of boolean attributes, where their mere existence implies `true`, `v-bind` works a little differently. In this example:
57+
No caso de atributos _booleanos_, onde sua mera existência implica em `true`, `v-bind` funciona um pouco diferente. Neste exemplo:
5858

5959
```html
60-
<button v-bind:disabled="isButtonDisabled">Button</button>
60+
<button v-bind:disabled="isButtonDisabled">Botão</button>
6161
```
6262

63-
If `isButtonDisabled` has the value of `null` or `undefined`, the `disabled` attribute will not even be included in the rendered `<button>` element.
63+
Se `isButtonDisabled` possui um valor `null` ou `undefined`, o atributo `disabled` nem mesmo será incluído no elemento `<button>` renderizado.
6464

65-
### Using JavaScript Expressions
65+
### Usando Expressões JavaScript
6666

67-
So far we've only been binding to simple property keys in our templates. But Vue.js actually supports the full power of JavaScript expressions inside all data bindings:
67+
Até aqui nós apenas vinculamos valores a chaves simples em nossos _templates_. Mas o Vue.js suporta todo o poder das expressões JavaScript dentro de todo tipo de vinculação de dados:
6868

6969
```html
70-
{{ number + 1 }} {{ ok ? 'YES' : 'NO' }} {{ message.split('').reverse().join('')
70+
{{ number + 1 }} {{ ok ? 'SIM' : 'NÃO' }} {{ message.split('').reverse().join('')
7171
}}
7272

7373
<div v-bind:id="'list-' + id"></div>
7474
```
7575

76-
These expressions will be evaluated as JavaScript in the data scope of the current active instance. One restriction is that each binding can only contain **one single expression**, so the following will **NOT** work:
76+
Estas expressões serão compiladas como JavaScript no escopo de dados da atual instância ativa do Vue. A única restrição é que cada vínculo pode conter **apenas uma expressão** - desta forma, os códigos a seguir são exemplos de coisas que **NÃO** funcionarão:
7777

7878
```html
79-
<!-- this is a statement, not an expression: -->
79+
<!-- isso é uma atribuição, não uma expressão: -->
8080
{{ var a = 1 }}
8181

82-
<!-- flow control won't work either, use ternary expressions -->
82+
<!-- ifs também não funcionarão, use expressões ternárias -->
8383
{{ if (ok) { return message } }}
8484
```
8585

86-
## Directives
86+
## Diretivas
8787

88-
Directives are special attributes with the `v-` prefix. Directive attribute values are expected to be **a single JavaScript expression** (with the exception of `v-for` and `v-on`, which will be discussed later). A directive's job is to reactively apply side effects to the DOM when the value of its expression changes. Let's review the example we saw in the introduction:
88+
Diretivas são atributos especiais com o prefixo `v-`. Espera-se que os valores atribuídos às diretivas sejam **uma única expressão JavaScript** (com a exceção do `v-for` e do `v-on`, que serão discutidos posteriormente). O trabalho de uma diretiva é aplicar reativamente efeitos colaterais ao DOM quando o valor de sua expressão muda. Vamos revisar o exemplo que vimos na introdução:
8989

9090
```html
91-
<p v-if="seen">Now you see me</p>
91+
<p v-if="seen">Agora você me vê</p>
9292
```
9393

94-
Here, the `v-if` directive would remove/insert the `<p>` element based on the truthiness of the value of the expression `seen`.
94+
Aqui, a diretiva `v-if` irá remover/inserir o elemento `<p>` baseado na veracidade do valor da expressão `seen`.
9595

96-
### Arguments
96+
### Parâmetros
9797

98-
Some directives can take an "argument", denoted by a colon after the directive name. For example, the `v-bind` directive is used to reactively update an HTML attribute:
98+
Algumas diretivas podem aceitar um parâmetro, denotado pelo símbolo de dois pontos após o nome da diretiva. Por exemplo, a diretiva `v-bind` é utilizada para atualizar um atributo HTML reativamente:
9999

100100
```html
101101
<a v-bind:href="url"> ... </a>
102102
```
103103

104-
Here `href` is the argument, which tells the `v-bind` directive to bind the element's `href` attribute to the value of the expression `url`.
104+
Aqui, `href` é o parâmetro que informará a diretiva `v-bind` para interligar o atributo `href` do elemento ao valor da expressão `url`.
105105

106-
Another example is the `v-on` directive, which listens to DOM events:
106+
Outro exemplo é a diretiva `v-on`, que observa eventos do DOM:
107107

108108
```html
109109
<a v-on:click="doSomething"> ... </a>
110110
```
111111

112-
Here the argument is the event name to listen to. We will talk about event handling in more detail too.
112+
Aqui, o argumento é o nome do evento do DOM que ela deverá escutar. Falaremos sobre gerenciamento de eventos em mais detalhes também.
113113

114-
### Dynamic Arguments
114+
### Argumentos Dinâmicos
115115

116-
It is also possible to use a JavaScript expression in a directive argument by wrapping it with square brackets:
116+
Também é possível usar uma expressão JavaScript no argumento de uma diretiva envolvendo-a em colchetes:
117117

118118
```html
119119
<!--
120-
Note that there are some constraints to the argument expression, as explained
121-
in the "Dynamic Argument Expression Constraints" section below.
120+
Note que existem algumas restrições à expressão do argumento, como explicado na seção
121+
"Restrições da Expressão de Argumento Dinâmico" abaixo.
122122
-->
123123
<a v-bind:[attributeName]="url"> ... </a>
124124
```
125125

126-
Here `attributeName` will be dynamically evaluated as a JavaScript expression, and its evaluated value will be used as the final value for the argument. For example, if your application instance has a data property, `attributeName`, whose value is `"href"`, then this binding will be equivalent to `v-bind:href`.
126+
Aqui, `attributeName` será dinamicamente processado como uma expressão JavaScript, e seu valor processado será usado como o valor final para o argumento. Por exemplo, se a instância da sua aplicação possui uma propriedade de dados `attributeName` cujo valor é `"href"`, então essa ligação irá ser equivalente a `v-bind:href`.
127127

128-
Similarly, you can use dynamic arguments to bind a handler to a dynamic event name:
128+
Da mesma forma, você pode usar argumentos dinâmicos para vincular um manipulador (_handler_) a um nome de evento dinâmico:
129129

130130
```html
131131
<a v-on:[eventName]="doSomething"> ... </a>
132132
```
133133

134-
In this example, when `eventName`'s value is `"focus"`, `v-on:[eventName]` will be equivalent to `v-on:focus`.
134+
Neste exemplo, quando o valor de `eventName` for `"focus"`, por exemplo, `v-on:[eventName]` será equivalente a `v-on:focus`.
135135

136-
### Modifiers
136+
### Modificadores
137137

138-
Modifiers are special postfixes denoted by a dot, which indicate that a directive should be bound in some special way. For example, the `.prevent` modifier tells the `v-on` directive to call `event.preventDefault()` on the triggered event:
138+
Modificadores são sufixos especiais denotados por um ponto `.`, que indicam que a diretiva deve ser aplicada de alguma maneira especial. Por exemplo, o modificador `.prevent` diz para a diretiva `v-on` chamar `event.preventDefault()` no evento desencadeado:
139139

140140
```html
141141
<form v-on:submit.prevent="onSubmit">...</form>
142142
```
143143

144-
You'll see other examples of modifiers later, [for `v-on`](events.md#event-modifiers) and [for `v-model`](forms.md#modifiers), when we explore those features.
144+
Você verá outros exemplos de modificadores posteriormente, [para a diretiva `v-on`](events.md#event-modifiers) e [para a diretiva `v-model`](forms.md#modifiers), quando explorarmos tais recursos.
145145

146-
## Shorthands
146+
## Abreviações
147147

148-
The `v-` prefix serves as a visual cue for identifying Vue-specific attributes in your templates. This is useful when you are using Vue.js to apply dynamic behavior to some existing markup, but can feel verbose for some frequently used directives. At the same time, the need for the `v-` prefix becomes less important when you are building a [SPA](https://en.wikipedia.org/wiki/Single-page_application), where Vue manages every template. Therefore, Vue provides special shorthands for two of the most often used directives, `v-bind` and `v-on`:
148+
O prefixo `v-` serve como uma dica visual para identificar atributos específicos do Vue em seus _templates_. Isso é útil quando você está utilizando Vue.js para aplicar comportamentos dinâmicos a alguma marcação existente, mas pode ser verboso para algumas diretivas usadas com frequência. Ao mesmo tempo, a necessidade do prefixo `v-` se torna menos importante quando você está construindo uma [SPA](https://en.wikipedia.org/wiki/Single-page_application), onde o Vue gerencia todas os _templates_. Desta forma, o Vue fornece abreviações especiais para duas das diretivas mais usadas, `v-bind` e `v-on`:
149149

150-
### `v-bind` Shorthand
150+
### Abreviação de `v-bind`
151151

152152
```html
153-
<!-- full syntax -->
153+
<!-- sintaxe completa -->
154154
<a v-bind:href="url"> ... </a>
155155

156-
<!-- shorthand -->
156+
<!-- forma abreviada -->
157157
<a :href="url"> ... </a>
158158

159-
<!-- shorthand with dynamic argument -->
159+
<!-- forma abreviada com argumento dinâmico -->
160160
<a :[key]="url"> ... </a>
161161
```
162162

163-
### `v-on` Shorthand
163+
### Abreviação de `v-on`
164164

165165
```html
166-
<!-- full syntax -->
166+
<!-- sintaxe completa -->
167167
<a v-on:click="doSomething"> ... </a>
168168

169-
<!-- shorthand -->
169+
<!-- forma abreviada -->
170170
<a @click="doSomething"> ... </a>
171171

172-
<!-- shorthand with dynamic argument (2.6.0+) -->
172+
<!-- forma abreviada com argumento dinâmico (2.6.0+) -->
173173
<a @[event]="doSomething"> ... </a>
174174
```
175175

176-
They may look a bit different from normal HTML, but `:` and `@` are valid characters for attribute names and all Vue-supported browsers can parse it correctly. In addition, they do not appear in the final rendered markup. The shorthand syntax is totally optional, but you will likely appreciate it when you learn more about its usage later.
176+
Eles podem parecer um pouco diferentes de HTML normal, mas `:` e `@` são caracteres válidos para nomes de atributos e todos os navegadores que suportam o Vue podem lê-los corretamente. Além do mais, eles não aparecem na marcação renderizada final. A sintaxe abreviada é totalmente opcional, mas você provavelmente vai preferir utilizá-la quando aprender mais sobre seu uso posteriormente.
177177

178-
> From the next page on, we'll use the shorthand in our examples, as that's the most common usage for Vue developers.
178+
> A partir da próxima página e em diante, iremos utilizar as formas abreviadas em nossos exemplos, já que é o uso mais comum para os desenvolvedores Vue.
179179
180-
### Caveats
180+
### Ressalvas
181181

182-
#### Dynamic Argument Value Constraints
182+
#### Restrições de Valores de Argumentos Dinâmicos
183183

184-
Dynamic arguments are expected to evaluate to a string, with the exception of `null`. The special value `null` can be used to explicitly remove the binding. Any other non-string value will trigger a warning.
184+
Espera-se que argumentos dinâmicos sejam avaliados resultando-se em uma String, com exceção do `null`. O valor especial `null` pode ser usado para explicitamente remover um vínculo. Qualquer outro valor que não seja uma String acionará um aviso.
185185

186-
#### Dynamic Argument Expression Constraints
186+
#### Restrições de Expressões de Argumentos Dinâmicos
187187

188-
Dynamic argument expressions have some syntax constraints because certain characters, such as spaces and quotes, are invalid inside HTML attribute names. For example, the following is invalid:
188+
Expressões de argumentos dinâmicos possuem algumas restrições de sintaxe por causa de determinados caracteres, como espaços e aspas, os quais são inválidos dentro de nomes de atributos HTML. Por exemplo, o seguinte é inválido:
189189

190190
```html
191-
<!-- This will trigger a compiler warning. -->
191+
<!-- Isto irá provocar um aviso do compilador. -->
192192
<a v-bind:['foo' + bar]="value"> ... </a>
193193
```
194194

195-
We recommend replacing any complex expressions with a [computed property](computed.html), one of the most fundamental pieces of Vue, which we'll cover shortly.
195+
Nós recomendamos trocar quaisquer expressões complexas por [dados computados](computed.html), uma das partes mais fundamentais do Vue, que cobriremos em breve.
196196

197-
When using in-DOM templates (templates directly written in an HTML file), you should also avoid naming keys with uppercase characters, as browsers will coerce attribute names into lowercase:
197+
Quando estiver usando _templates_ no DOM (_templates_ escritos diretamente no arquivo HTML), você também deve evitar nomear suas chaves de argumentos com caracteres maiúsculos, já que os navegadores forçarão os nomes dos atributos a ficarem em minúsculas:
198198

199199
```html
200200
<!--
201-
This will be converted to v-bind:[someattr] in in-DOM templates.
202-
Unless you have a "someattr" property in your instance, your code won't work.
201+
Isso será convertido em v-bind:[someattr] em templates no DOM.
202+
A menos que você tenha uma propriedade "someattr" (totalmente em minúsculas) em sua instância, tal código não funcionará.
203203
-->
204204
<a v-bind:[someAttr]="value"> ... </a>
205205
```
206206

207-
#### JavaScript Expressions
207+
#### Expressões JavaScript
208208

209-
Template expressions are sandboxed and only have access to a [whitelist of globals](https://github.com/vuejs/vue-next/blob/master/packages/shared/src/globalsWhitelist.ts#L3) such as `Math` and `Date`. You should not attempt to access user defined globals in template expressions.
209+
Expressões de _template_ são isoladas e possuem acesso apenas à uma [lista de variáveis globais permitidas](https://github.com/vuejs/vue-next/blob/master/packages/shared/src/globalsWhitelist.ts#L3), tais como `Math` e `Date`. Você não deve tentar acessar variáveis globais definidas pelo usuário em expressões de _template_.

0 commit comments

Comments
 (0)