|
1 |
| -# Instance Methods |
| 1 | +# Métodos de Instância |
2 | 2 |
|
3 | 3 | ## $watch
|
4 | 4 |
|
5 |
| -- **Arguments:** |
| 5 | +- **Argumentos:** |
6 | 6 |
|
7 | 7 | - `{string | Function} source`
|
8 | 8 | - `{Function | Object} callback`
|
|
11 | 11 | - `{boolean} immediate`
|
12 | 12 | - `{string} flush`
|
13 | 13 |
|
14 |
| -- **Returns:** `{Function} unwatch` |
| 14 | +- **Retorno:** `{Function} unwatch` |
15 | 15 |
|
16 |
| -- **Usage:** |
| 16 | +- **Uso:** |
17 | 17 |
|
18 |
| - Watch a reactive property or a computed function on the component instance for changes. The callback gets called with the new value and the old value for the given property. We can only pass top-level `data`, `props`, or `computed` property name as a string. For more complex expressions or nested properties, use a function instead. |
| 18 | + Observa uma propriedade reativa ou uma função computada na instância do componente esperando alterações. O _callback_ é chamado com o novo valor e o valor antigo para a propriedade fornecida. Só podemos passar o nome da propriedade `data`, `props` ou `computed` de nível superior como uma string. Para expressões mais complexas ou propriedades aninhadas, use uma função. |
19 | 19 |
|
20 |
| -- **Example:** |
| 20 | +- **Exemplo:** |
21 | 21 |
|
22 | 22 | ```js
|
23 | 23 | const app = createApp({
|
|
32 | 32 | }
|
33 | 33 | },
|
34 | 34 | created() {
|
35 |
| - // top-level property name |
| 35 | + // nome da propriedade de nível superior |
36 | 36 | this.$watch('a', (newVal, oldVal) => {
|
37 |
| - // do something |
| 37 | + // faça algo |
38 | 38 | })
|
39 | 39 |
|
40 |
| - // function for watching a single nested property |
| 40 | + // função para observar uma única propriedade aninhada |
41 | 41 | this.$watch(
|
42 | 42 | () => this.c.d,
|
43 | 43 | (newVal, oldVal) => {
|
44 |
| - // do something |
| 44 | + // faça algo |
45 | 45 | }
|
46 | 46 | )
|
47 | 47 |
|
48 |
| - // function for watching a complex expression |
| 48 | + // função para observar uma expressão complexa |
49 | 49 | this.$watch(
|
50 |
| - // every time the expression `this.a + this.b` yields a different result, |
51 |
| - // the handler will be called. It's as if we were watching a computed |
52 |
| - // property without defining the computed property itself |
| 50 | + // toda vez que a expressão `this.a + this.b` produz um resultado diferente, |
| 51 | + // o manipulador será chamado. É como se estivéssemos observando |
| 52 | + // um dado computado sem precisarmos definí-lo |
53 | 53 | () => this.a + this.b,
|
54 | 54 | (newVal, oldVal) => {
|
55 |
| - // do something |
| 55 | + // faça algo |
56 | 56 | }
|
57 | 57 | )
|
58 | 58 | }
|
59 | 59 | })
|
60 | 60 | ```
|
61 | 61 |
|
62 |
| - When watched value is an object or array, any changes to its properties or elements won't trigger the watcher because they reference the same object/array: |
| 62 | + Quando o valor observado é um objeto ou array, quaisquer alterações em suas propriedades ou elementos não acionarão o inspetor porque fazem referência ao mesmo objeto/array: |
63 | 63 |
|
64 | 64 | ```js
|
65 | 65 | const app = createApp({
|
66 | 66 | data() {
|
67 | 67 | return {
|
68 | 68 | article: {
|
69 |
| - text: 'Vue is awesome!' |
| 69 | + text: 'Vue é incrível!' |
70 | 70 | },
|
71 |
| - comments: ['Indeed!', 'I agree'] |
| 71 | + comments: ['De fato!', 'Concordo'] |
72 | 72 | }
|
73 | 73 | },
|
74 | 74 | created() {
|
75 | 75 | this.$watch('article', () => {
|
76 |
| - console.log('Article changed!') |
| 76 | + console.log('Artigo alterado!') |
77 | 77 | })
|
78 | 78 |
|
79 | 79 | this.$watch('comments', () => {
|
80 |
| - console.log('Comments changed!') |
| 80 | + console.log('Comentários alterados!') |
81 | 81 | })
|
82 | 82 | },
|
83 | 83 | methods: {
|
84 |
| - // These methods won't trigger a watcher because we changed only a property of object/array, |
85 |
| - // not the object/array itself |
| 84 | + // Esses métodos não acionarão um observador pois alteramos apenas uma propriedade do object/array, |
| 85 | + // não o objeto/array em si |
86 | 86 | changeArticleText() {
|
87 |
| - this.article.text = 'Vue 3 is awesome' |
| 87 | + this.article.text = 'Vue 3 é incrível' |
88 | 88 | },
|
89 | 89 | addComment() {
|
90 |
| - this.comments.push('New comment') |
| 90 | + this.comments.push('Novo comentário') |
91 | 91 | },
|
92 | 92 |
|
93 |
| - // These methods will trigger a watcher because we replaced object/array completely |
| 93 | + // Esses métodos acionarão um observador pois substituímos o objeto/array completamente |
94 | 94 | changeWholeArticle() {
|
95 |
| - this.article = { text: 'Vue 3 is awesome' } |
| 95 | + this.article = { text: 'Vue 3 é incrível' } |
96 | 96 | },
|
97 | 97 | clearComments() {
|
98 | 98 | this.comments = []
|
|
101 | 101 | })
|
102 | 102 | ```
|
103 | 103 |
|
104 |
| - `$watch` returns an unwatch function that stops firing the callback: |
| 104 | + `$watch` retorna uma função `unwatch` que para de disparar o _callback_: |
105 | 105 |
|
106 | 106 | ```js
|
107 | 107 | const app = createApp({
|
|
115 | 115 | const vm = app.mount('#app')
|
116 | 116 |
|
117 | 117 | const unwatch = vm.$watch('a', cb)
|
118 |
| - // later, teardown the watcher |
| 118 | + // depois, desmonta o observador |
119 | 119 | unwatch()
|
120 | 120 | ```
|
121 | 121 |
|
122 |
| -- **Option: deep** |
| 122 | +- **Opção: `deep`** |
123 | 123 |
|
124 |
| - To also detect nested value changes inside Objects, you need to pass in `deep: true` in the options argument. This option also can be used to watch array mutations. |
| 124 | + Para também detectar mudanças de valores aninhados dentro de Objects, você precisa passar `deep: true` no argumento de opções. Esta opção também pode ser usada para observar mutações de array. |
125 | 125 |
|
126 |
| - > Note: when mutating (rather than replacing) an Object or an Array and watch with deep option, the old value will be the same as new value because they reference the same Object/Array. Vue doesn't keep a copy of the pre-mutate value. |
| 126 | + > Nota: ao mudar (ao invés de substituir) um Object ou um Array e observar com a opção `deep`, o valor antigo será o mesmo que o novo valor porque eles fazem referência ao mesmo Object/Array. O Vue não mantém uma cópia do valor pré-modificação. |
127 | 127 |
|
128 | 128 | ```js
|
129 | 129 | vm.$watch('someObject', callback, {
|
130 | 130 | deep: true
|
131 | 131 | })
|
132 | 132 | vm.someObject.nestedValue = 123
|
133 |
| - // callback is fired |
| 133 | + // callback é acionado |
134 | 134 | ```
|
135 | 135 |
|
136 |
| -- **Option: immediate** |
| 136 | +- **Opção: `immediate`** |
137 | 137 |
|
138 |
| - Passing in `immediate: true` in the option will trigger the callback immediately with the current value of the expression: |
| 138 | + Passar `immediate: true` na opção acionará o _callback_ imediatamente com o valor atual da expressão: |
139 | 139 |
|
140 | 140 | ```js
|
141 | 141 | vm.$watch('a', callback, {
|
142 | 142 | immediate: true
|
143 | 143 | })
|
144 |
| - // `callback` is fired immediately with current value of `a` |
| 144 | + // `callback` é acionado imediatamente com o valor atual de `a` |
145 | 145 | ```
|
146 | 146 |
|
147 |
| - Note that with `immediate` option you won't be able to unwatch the given property on the first callback call. |
| 147 | + Observe que com a opção `immediate` você não poderá dar _unwatch_ na propriedade fornecida na primeira chamada de _callback_. |
148 | 148 |
|
149 | 149 | ```js
|
150 |
| - // This will cause an error |
| 150 | + // Isso causará um erro |
151 | 151 | const unwatch = vm.$watch(
|
152 | 152 | 'value',
|
153 | 153 | function() {
|
|
158 | 158 | )
|
159 | 159 | ```
|
160 | 160 |
|
161 |
| - If you still want to call an unwatch function inside the callback, you should check its availability first: |
| 161 | + Se você ainda quiser chamar uma função _unwatch_ dentro do _callback_, verifique primeiro sua disponibilidade: |
162 | 162 |
|
163 | 163 | ```js
|
164 | 164 | let unwatch = null
|
|
175 | 175 | )
|
176 | 176 | ```
|
177 | 177 |
|
178 |
| -- **Option: flush** |
| 178 | +- **Opção: flush** |
179 | 179 |
|
180 |
| - The `flush` option allows for greater control over the timing of the callback. It can be set to `'pre'`, `'post'` or `'sync'`. |
| 180 | + A opção `flush` permite maior controle sobre o momento de acionamento do _callback_. Pode ser definido como `'pre'`, `'post'` ou `'sync'`. |
181 | 181 |
|
182 |
| - The default value is `'pre'`, which specifies that the callback should be invoked before rendering. This allows the callback to update other values before the template runs. |
| 182 | + O valor padrão é `'pre'`, que especifica que o _callback_ deve ser invocado antes da renderização. Isso permite que o _callback_ atualize outros valores antes que o _template_ seja executado. |
183 | 183 |
|
184 |
| - The value `'post'` can be used to defer the callback until after rendering. This should be used if the callback needs access to the updated DOM or child components via `$refs`. |
| 184 | + O valor `'post'` pode ser usado para adiar o _callback_ até depois da renderização. Isso deve ser usado se o _callback_ precisar acessar o DOM atualizado ou componentes filho por meio de `$refs`. |
185 | 185 |
|
186 |
| - If `flush` is set to `'sync'`, the callback will be called synchronously, as soon as the value changes. |
| 186 | + Se `flush` for definido como `'sync'`, o _callback_ será chamado de forma síncrona, assim que o valor mudar. |
187 | 187 |
|
188 |
| - For both `'pre'` and `'post'`, the callback is buffered using a queue. The callback will only be added to the queue once, even if the watched value changes multiple times. The interim values will be skipped and won't be passed to the callback. |
| 188 | + Para ambos `'pre'` e `'post'`, o _callback_ é armazenado em _buffer_ usando uma fila. O _callback_ será adicionado à fila apenas uma vez, mesmo que o valor observado seja alterado várias vezes. Os valores provisórios serão ignorados e não serão passados para o _callback_. |
189 | 189 |
|
190 |
| - Buffering the callback not only improves performance but also helps to ensure data consistency. The watchers won't be triggered until the code performing the data updates has finished. |
| 190 | + O armazenamento em _buffer_ do _callback_ não apenas melhora o desempenho, mas também ajuda a garantir a consistência dos dados. Os observadores não serão acionados até que o código que executa as atualizações de dados seja concluído. |
191 | 191 |
|
192 |
| - `'sync'` watchers should be used sparingly, as they don't have these benefits. |
| 192 | + Observadores `'sync'` devem ser usados com moderação, pois eles não têm esses benefícios. |
193 | 193 |
|
194 |
| - For more information about `flush` see [Effect Flush Timing](../guide/reactivity-computed-watchers.html#effect-flush-timing). |
| 194 | + Para obter mais informações sobre `flush`, consulte [Momento de Limpeza do Efeito](../guide/reactivity-computed-watchers.html#momento-de-limpeza-do-efeito). |
195 | 195 |
|
196 |
| -- **See also:** [Watchers](../guide/computed.html#watchers) |
| 196 | +- **Ver também:** [Observadores](../guide/computed.html#observadores) |
197 | 197 |
|
198 |
| -## $emit |
| 198 | +## `$emit` |
199 | 199 |
|
200 |
| -- **Arguments:** |
| 200 | +- **Argumentos:** |
201 | 201 |
|
202 | 202 | - `{string} eventName`
|
203 |
| - - `...args (optional)` |
| 203 | + - `...args (opcional)` |
204 | 204 |
|
205 |
| - Trigger an event on the current instance. Any additional arguments will be passed into the listener's callback function. |
| 205 | + Acionar um evento na instância atual. Quaisquer argumentos adicionais serão passados para a função _callback_ do escutador. |
206 | 206 |
|
207 |
| -- **Examples:** |
| 207 | +- **Exemplos:** |
208 | 208 |
|
209 |
| - Using `$emit` with only an event name: |
| 209 | + Usando `$emit` com apenas um nome de evento: |
210 | 210 |
|
211 | 211 | ```html
|
212 | 212 | <div id="emit-example-simple">
|
|
218 | 218 | const app = createApp({
|
219 | 219 | methods: {
|
220 | 220 | sayHi() {
|
221 |
| - console.log('Hi!') |
| 221 | + console.log('Oi!') |
222 | 222 | }
|
223 | 223 | }
|
224 | 224 | })
|
|
227 | 227 | emits: ['welcome'],
|
228 | 228 | template: `
|
229 | 229 | <button v-on:click="$emit('welcome')">
|
230 |
| - Click me to be welcomed |
| 230 | + Clique-me para as boas vindas |
231 | 231 | </button>
|
232 | 232 | `
|
233 | 233 | })
|
234 | 234 |
|
235 | 235 | app.mount('#emit-example-simple')
|
236 | 236 | ```
|
237 | 237 |
|
238 |
| - Using `$emit` with additional arguments: |
| 238 | + Usando `$emit` com argumentos adicionais: |
239 | 239 |
|
240 | 240 | ```html
|
241 | 241 | <div id="emit-example-argument">
|
|
256 | 256 | emits: ['advise'],
|
257 | 257 | data() {
|
258 | 258 | return {
|
259 |
| - adviceText: 'Some advice' |
| 259 | + adviceText: 'Alguns conselhos' |
260 | 260 | }
|
261 | 261 | },
|
262 | 262 | template: `
|
263 | 263 | <div>
|
264 | 264 | <input type="text" v-model="adviceText">
|
265 | 265 | <button v-on:click="$emit('advise', adviceText)">
|
266 |
| - Click me for sending advice |
| 266 | + Clique em mim para enviar conselhos |
267 | 267 | </button>
|
268 | 268 | </div>
|
269 | 269 | `
|
|
272 | 272 | app.mount('#emit-example-argument')
|
273 | 273 | ```
|
274 | 274 |
|
275 |
| -- **See also:** |
276 |
| - - [`emits` option](./options-data.html#emits) |
277 |
| - - [Emitting a Value With an Event](../guide/component-basics.html#emitting-a-value-with-an-event) |
| 275 | +- **Ver também:** |
| 276 | + - [Opção `emits`](./options-data.html#emits) |
| 277 | + - [Emitindo um Valor Com um Evento](../guide/component-basics.html#emitindo-um-valor-com-um-evento) |
278 | 278 |
|
279 |
| -## $forceUpdate |
| 279 | +## `$forceUpdate` |
280 | 280 |
|
281 |
| -- **Usage:** |
| 281 | +- **Uso:** |
282 | 282 |
|
283 |
| - Force the component instance to re-render. Note it does not affect all child components, only the instance itself and child components with inserted slot content. |
| 283 | + Força a instância do componente a renderizar novamente. Observe que isso não afeta todos os componentes filho, apenas a própria instância e os componentes filho com conteúdo de _slot_ inserido. |
284 | 284 |
|
285 |
| -## $nextTick |
| 285 | +## `$nextTick` |
286 | 286 |
|
287 |
| -- **Arguments:** |
| 287 | +- **Argumentos:** |
288 | 288 |
|
289 |
| - - `{Function} callback (optional)` |
| 289 | + - `{Function} callback (opcional)` |
290 | 290 |
|
291 |
| -- **Usage:** |
| 291 | +- **Uso:** |
292 | 292 |
|
293 |
| - Defer the callback to be executed after the next DOM update cycle. Use it immediately after you've changed some data to wait for the DOM update. This is the same as the global `nextTick`, except that the callback's `this` context is automatically bound to the instance calling this method. |
| 293 | + Adie o _callback_ para ser executado após o próximo ciclo de atualização do DOM. Use-o imediatamente após alterar alguns dados para aguardar a atualização do DOM. Isso é o mesmo que o `nextTick` global, exceto que o contexto `this` do _callback_ é automaticamente vinculado à instância que chama esse método. |
294 | 294 |
|
295 |
| -- **Example:** |
| 295 | +- **Exemplo:** |
296 | 296 |
|
297 | 297 | ```js
|
298 | 298 | createApp({
|
299 | 299 | // ...
|
300 | 300 | methods: {
|
301 | 301 | // ...
|
302 | 302 | example() {
|
303 |
| - // modify data |
| 303 | + // modifica os dados |
304 | 304 | this.message = 'changed'
|
305 |
| - // DOM is not updated yet |
| 305 | + // DOM ainda não foi atualizado |
306 | 306 | this.$nextTick(function() {
|
307 |
| - // DOM is now updated |
308 |
| - // `this` is bound to the current instance |
| 307 | + // DOM agora está atualizado |
| 308 | + // `this` está vinculado à instância atual |
309 | 309 | this.doSomethingElse()
|
310 | 310 | })
|
311 | 311 | }
|
312 | 312 | }
|
313 | 313 | })
|
314 | 314 | ```
|
315 | 315 |
|
316 |
| -- **See also:** [nextTick](global-api.html#nexttick) |
| 316 | +- **Ver também:** [nextTick](global-api.html#nexttick) |
0 commit comments