|
1 |
| -# Template Syntax |
| 1 | +# Sintaxe de Templates |
2 | 2 |
|
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. |
4 | 4 |
|
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. |
6 | 6 |
|
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. |
8 | 8 |
|
9 |
| -## Interpolations |
| 9 | +## Interpolações |
10 | 10 |
|
11 |
| -### Text |
| 11 | +### Texto |
12 | 12 |
|
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): |
14 | 14 |
|
15 | 15 | ```html
|
16 |
| -<span>Message: {{ msg }}</span> |
| 16 | +<span>Mensagem: {{ msg }}</span> |
17 | 17 | ```
|
18 | 18 |
|
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. |
20 | 20 |
|
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ó: |
22 | 22 |
|
23 | 23 | ```html
|
24 |
| -<span v-once>This will never change: {{ msg }}</span> |
| 24 | +<span v-once>Este valor nunca será modificado: {{ msg }}</span> |
25 | 25 | ```
|
26 | 26 |
|
27 |
| -### Raw HTML |
| 27 | +### HTML Puro |
28 | 28 |
|
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): |
30 | 30 |
|
31 | 31 | ```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> |
34 | 34 | ```
|
35 | 35 |
|
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> |
40 | 40 | </p>
|
41 | 41 | <script async src="https://static.codepen.io/assets/embed/ei.js"></script>
|
42 | 42 |
|
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. |
44 | 44 |
|
45 | 45 | ::: 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. |
47 | 47 | :::
|
48 | 48 |
|
49 |
| -### Attributes |
| 49 | +### Atributos |
50 | 50 |
|
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)): |
52 | 52 |
|
53 | 53 | ```html
|
54 | 54 | <div v-bind:id="dynamicId"></div>
|
55 | 55 | ```
|
56 | 56 |
|
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: |
58 | 58 |
|
59 | 59 | ```html
|
60 |
| -<button v-bind:disabled="isButtonDisabled">Button</button> |
| 60 | +<button v-bind:disabled="isButtonDisabled">Botão</button> |
61 | 61 | ```
|
62 | 62 |
|
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. |
64 | 64 |
|
65 |
| -### Using JavaScript Expressions |
| 65 | +### Usando Expressões JavaScript |
66 | 66 |
|
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: |
68 | 68 |
|
69 | 69 | ```html
|
70 |
| -{{ number + 1 }} {{ ok ? 'YES' : 'NO' }} {{ message.split('').reverse().join('') |
| 70 | +{{ number + 1 }} {{ ok ? 'SIM' : 'NÃO' }} {{ message.split('').reverse().join('') |
71 | 71 | }}
|
72 | 72 |
|
73 | 73 | <div v-bind:id="'list-' + id"></div>
|
74 | 74 | ```
|
75 | 75 |
|
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: |
77 | 77 |
|
78 | 78 | ```html
|
79 |
| -<!-- this is a statement, not an expression: --> |
| 79 | +<!-- isso é uma atribuição, não uma expressão: --> |
80 | 80 | {{ var a = 1 }}
|
81 | 81 |
|
82 |
| -<!-- flow control won't work either, use ternary expressions --> |
| 82 | +<!-- ifs também não funcionarão, use expressões ternárias --> |
83 | 83 | {{ if (ok) { return message } }}
|
84 | 84 | ```
|
85 | 85 |
|
86 |
| -## Directives |
| 86 | +## Diretivas |
87 | 87 |
|
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: |
89 | 89 |
|
90 | 90 | ```html
|
91 |
| -<p v-if="seen">Now you see me</p> |
| 91 | +<p v-if="seen">Agora você me vê</p> |
92 | 92 | ```
|
93 | 93 |
|
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`. |
95 | 95 |
|
96 |
| -### Arguments |
| 96 | +### Parâmetros |
97 | 97 |
|
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: |
99 | 99 |
|
100 | 100 | ```html
|
101 | 101 | <a v-bind:href="url"> ... </a>
|
102 | 102 | ```
|
103 | 103 |
|
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`. |
105 | 105 |
|
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: |
107 | 107 |
|
108 | 108 | ```html
|
109 | 109 | <a v-on:click="doSomething"> ... </a>
|
110 | 110 | ```
|
111 | 111 |
|
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. |
113 | 113 |
|
114 |
| -### Dynamic Arguments |
| 114 | +### Argumentos Dinâmicos |
115 | 115 |
|
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: |
117 | 117 |
|
118 | 118 | ```html
|
119 | 119 | <!--
|
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. |
122 | 122 | -->
|
123 | 123 | <a v-bind:[attributeName]="url"> ... </a>
|
124 | 124 | ```
|
125 | 125 |
|
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`. |
127 | 127 |
|
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: |
129 | 129 |
|
130 | 130 | ```html
|
131 | 131 | <a v-on:[eventName]="doSomething"> ... </a>
|
132 | 132 | ```
|
133 | 133 |
|
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`. |
135 | 135 |
|
136 |
| -### Modifiers |
| 136 | +### Modificadores |
137 | 137 |
|
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: |
139 | 139 |
|
140 | 140 | ```html
|
141 | 141 | <form v-on:submit.prevent="onSubmit">...</form>
|
142 | 142 | ```
|
143 | 143 |
|
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. |
145 | 145 |
|
146 |
| -## Shorthands |
| 146 | +## Abreviações |
147 | 147 |
|
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`: |
149 | 149 |
|
150 |
| -### `v-bind` Shorthand |
| 150 | +### Abreviação de `v-bind` |
151 | 151 |
|
152 | 152 | ```html
|
153 |
| -<!-- full syntax --> |
| 153 | +<!-- sintaxe completa --> |
154 | 154 | <a v-bind:href="url"> ... </a>
|
155 | 155 |
|
156 |
| -<!-- shorthand --> |
| 156 | +<!-- forma abreviada --> |
157 | 157 | <a :href="url"> ... </a>
|
158 | 158 |
|
159 |
| -<!-- shorthand with dynamic argument --> |
| 159 | +<!-- forma abreviada com argumento dinâmico --> |
160 | 160 | <a :[key]="url"> ... </a>
|
161 | 161 | ```
|
162 | 162 |
|
163 |
| -### `v-on` Shorthand |
| 163 | +### Abreviação de `v-on` |
164 | 164 |
|
165 | 165 | ```html
|
166 |
| -<!-- full syntax --> |
| 166 | +<!-- sintaxe completa --> |
167 | 167 | <a v-on:click="doSomething"> ... </a>
|
168 | 168 |
|
169 |
| -<!-- shorthand --> |
| 169 | +<!-- forma abreviada --> |
170 | 170 | <a @click="doSomething"> ... </a>
|
171 | 171 |
|
172 |
| -<!-- shorthand with dynamic argument (2.6.0+) --> |
| 172 | +<!-- forma abreviada com argumento dinâmico (2.6.0+) --> |
173 | 173 | <a @[event]="doSomething"> ... </a>
|
174 | 174 | ```
|
175 | 175 |
|
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. |
177 | 177 |
|
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. |
179 | 179 |
|
180 |
| -### Caveats |
| 180 | +### Ressalvas |
181 | 181 |
|
182 |
| -#### Dynamic Argument Value Constraints |
| 182 | +#### Restrições de Valores de Argumentos Dinâmicos |
183 | 183 |
|
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. |
185 | 185 |
|
186 |
| -#### Dynamic Argument Expression Constraints |
| 186 | +#### Restrições de Expressões de Argumentos Dinâmicos |
187 | 187 |
|
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: |
189 | 189 |
|
190 | 190 | ```html
|
191 |
| -<!-- This will trigger a compiler warning. --> |
| 191 | +<!-- Isto irá provocar um aviso do compilador. --> |
192 | 192 | <a v-bind:['foo' + bar]="value"> ... </a>
|
193 | 193 | ```
|
194 | 194 |
|
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. |
196 | 196 |
|
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: |
198 | 198 |
|
199 | 199 | ```html
|
200 | 200 | <!--
|
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á. |
203 | 203 | -->
|
204 | 204 | <a v-bind:[someAttr]="value"> ... </a>
|
205 | 205 | ```
|
206 | 206 |
|
207 |
| -#### JavaScript Expressions |
| 207 | +#### Expressões JavaScript |
208 | 208 |
|
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