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/api/options-lifecycle-hooks.md
+83-83Lines changed: 83 additions & 83 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,187 +1,187 @@
1
-
# Lifecycle hooks
1
+
# Gatilhos de Ciclo de vida
2
2
3
-
:::tip Note
4
-
All lifecycle hooks automatically have their `this`context bound to the instance, so that you can access data, computed properties, and methods. This means **you should not use an arrow function to define a lifecycle method** (e.g.`created: () => this.fetchTodos()`). The reason is arrow functions bind the parent context, so `this`will not be the component instance as you expect and `this.fetchTodos`will be undefined.
3
+
:::Dica
4
+
Todos gatilhos de ciclo de vida têm seu contexto `this`vinculado automaticamente à instância, de forma que você pode acessar dados, propriedades computadas e métodos. Isso significa que **você não deve usar uma _arrow function_ para definir um método de ciclo de vida** (exemplo:`created: () => this.fetchTodos()`). A justificativa é que _arrow functions_ vinculam o contexto pai, então o `this`não será a instância que você espera e o `this.fetchTodos`será `undefined`.
5
5
:::
6
6
7
7
## beforeCreate
8
8
9
-
-**Type:**`Function`
9
+
-**Tipo:**`Function`
10
10
11
-
-**Details:**
11
+
-**Detalhes:**
12
12
13
-
Called synchronously immediately after the instance has been initialized, before data observation and event/watcher setup.
13
+
Invocado sincronamente logo após a instância ser inicializada e antes da observação dos dados e configuração de eventos e observadores.
-**Ver também:**[Diagrama de ciclo de vida](../guide/instance.html#lifecycle-diagram)
16
16
17
17
## created
18
18
19
-
-**Type:**`Function`
19
+
-**Tipo:**`Function`
20
20
21
-
-**Details:**
21
+
-**Detalhes:**
22
22
23
-
Called synchronously after the instance is created. At this stage, the instance has finished processing the options which means the following have been set up: data observation, computed properties, methods, watch/event callbacks. However, the mounting phase has not been started, and the `$el`property will not be available yet.
23
+
Invocado sincronamente após a instância ser criada. Nesse estágio, a instância finalizou o processamento das opções, o que significa que a observação de dados, propriedades computadas, métodos e _callbacks_ de observação e eventos foram inicializados. Entretanto, a fase de montagem não foi iniciada, e a propriedade `$el`não estará disponível ainda.
-**Ver também:**[Diagrama de ciclo de vida](../guide/instance.html#lifecycle-diagram)
38
38
39
39
## mounted
40
40
41
-
-**Type:**`Function`
41
+
-**Tipo:**`Function`
42
42
43
-
-**Details:**
43
+
-**Detalhes:**
44
44
45
-
Called after the instance has been mounted, where element, passed to `Vue.createApp({}).mount()` is replaced by the newly created `vm.$el`. If the root instance is mounted to an in-document element, `vm.$el`will also be in-document when `mounted`is called.
45
+
Invocado após a instância ser montada, onde `el`, passado para o `Vue.createApp({}).mount()`, é substituído pelo recém criado `vm.$el`. Se a instância raiz for montada em um elemento presente no documento, `vm.$el`também estará no documento quando o `mounted`for invocado.
46
46
47
-
Note that `mounted`does **not**guarantee that all child components have also been mounted. If you want to wait until the entire view has been rendered, you can use [vm.\$nextTick](../api/instance-methods.html#nexttick)inside of`mounted`:
47
+
Perceba que o `mounted`**não**garante que todos componentes filhos foram também montados. Se você quiser esperar até que toda a _view_ tenha sido renderizada, você pode usar o [vm.\$nextTick](../api/instance-methods.html#nexttick)dentro do`mounted`:
48
48
49
49
```js
50
50
mounted() {
51
51
this.$nextTick(function () {
52
-
//Code that will run only after the
53
-
//entire view has been rendered
52
+
//Código que só será executado depois
53
+
//de a view inteira ter sido renderizada
54
54
})
55
55
}
56
56
```
57
57
58
-
**This hook is not called during server-side rendering.**
58
+
**Esse gatilho não é invocado durante a renderização do lado do servidor.**
-**Ver também:**[Diagrama de ciclo de vida](../guide/instance.html#lifecycle-diagram)
61
61
62
62
## beforeUpdate
63
63
64
-
-**Type:**`Function`
64
+
-**Tipo:**`Function`
65
65
66
-
-**Details:**
66
+
-**Detalhes:**
67
67
68
-
Called when data changes, before the DOM is patched. This is a good place to access the existing DOM before an update, e.g. to remove manually added event listeners.
68
+
Invocado quando há mudança nos dados e antes de o DOM ser atualizado. Esse é um bom momento para acessar a DOM existente antes de uma atualização, por exemplo, para remover escutas de evento adicionadas manualmente.
69
69
70
-
**This hook is not called during server-side rendering, because only the initial render is performed server-side.**
70
+
**Esse gatilho não é invocado durante a renderização do lado do servidor, porque apenas a renderização inicial é realizada do lado do servidor.**
-**Ver também:**[Diagrama de ciclo de vida](../guide/instance.html#lifecycle-diagram)
73
73
74
74
## updated
75
75
76
-
-**Type:**`Function`
76
+
-**Tipo:**`Function`
77
77
78
-
-**Details:**
78
+
-**Detalhes:**
79
79
80
-
Called after a data change causes the virtual DOM to be re-rendered and patched.
80
+
Invocado após uma mudança nos dados causar uma re-renderização do DOM.
81
81
82
-
The component's DOM will have been updated when this hook is called, so you can perform DOM-dependent operations here. However, in most cases you should avoid changing state inside the hook. To react to state changes, it's usually better to use a [computed property](./options-data.html#computed)or [watcher](./options-data.html#watch) instead.
82
+
O DOM do componente terá sido atualizado quando esse gatilho for invocado, de forma que você pode realizar operações dependentes do DOM neste gatilho. Entretanto, na maioria dos casos você deve evitar mudanças de estado dentro do gatilho. Para reagir à mudanças de estado, normalmente é melhor usar uma [propriedade computada](./options-data.html#computed)ou um [observador](./options-data.html#watch).
83
83
84
-
Note that `updated`does **not**guarantee that all child components have also been re-rendered. If you want to wait until the entire view has been re-rendered, you can use [vm.\$nextTick](../api/instance-methods.html#nexttick)inside of`updated`:
84
+
Perceba que o `updated`**não**garante que todos componentes filhos foram também re-renderizados. Se você quiser esperar até que toda _view_ tenha sido re-renderizada, você pode usar o [vm.\$nextTick](../api/instance-methods.html#nexttick)dentro do`updated`:
85
85
86
86
```js
87
87
updated() {
88
88
this.$nextTick(function () {
89
-
//Code that will run only after the
90
-
//entire view has been re-rendered
89
+
//Código que só será executado depois
90
+
//de a view inteira ter sido re-renderizada
91
91
})
92
92
}
93
93
```
94
94
95
-
**This hook is not called during server-side rendering.**
95
+
**Esse gatilho não é invocado durante a renderização do lado do servidor.**
-**Ver também:**[Diagrama de ciclo de vida](../guide/instance.html#lifecycle-diagram)
136
136
137
137
## unmounted
138
138
139
-
-**Type:**`Function`
139
+
-**Tipo:**`Function`
140
140
141
-
-**Details:**
141
+
-**Detalhes:**
142
142
143
-
Called after a component instance has been unmounted. When this hook is called, all directives of the component instance have been unbound, all event listeners have been removed, and all child component instance have also been unmounted.
143
+
Invocada após uma instância ser desmontada. Quando esse gatilho é invocado, todas diretivas da instância já foram desligadas, todas escutas de evento foram removidas e todos componentes filhos também foram desmontados.
144
144
145
-
**This hook is not called during server-side rendering.**
145
+
**Esse gatilho não é invocado durante a renderização do lado do servidor.**
Called when an error from any descendent component is captured. The hook receives three arguments: the error, the component instance that triggered the error, and a string containing information on where the error was captured. The hook can return`false`to stop the error from propagating further.
155
+
Invocada quando um erro de qualquer componente descendente foi capturado. O gatilho recebe três argumentos: o erro, a instância que desencadeou o erro e uma _string_ contendo informações sobre onde o erro foi capturado. O gatilho pode retornar`false`para impedir que o erro continue a ser propagado.
156
156
157
-
:::tip
158
-
You can modify component state in this hook. However, it is important to have conditionals in your template or render function that short circuits other content when an error has been captured; otherwise the component will be thrown into an infinite render loop.
157
+
:::Dica
158
+
Você pode modificar o estado de um componente nesse gatilho. Entretanto, é importante possuir condicionais em seu template ou função `render` que bloqueiem outras mudanças quando um erro for capturado; caso contrário, o componente pode entrar em um loop de renderização infinito.
159
159
:::
160
160
161
-
**Error Propagation Rules**
161
+
**Regras de propagação de erro**
162
162
163
-
-By default, all errors are still sent to the global `config.errorHandler`if it is defined, so that these errors can still be reported to an analytics service in a single place.
163
+
-Por padrão, todos erros são enviados ao `config.errorHandler`global caso esteja definido, de forma que esses erros possam ainda ser reportados para um serviço de _analytics_ em um lugar só.
164
164
165
-
-If multiple `errorCaptured`hooks exist on a component's inheritance chain or parent chain, all of them will be invoked on the same error.
165
+
-Caso existam vários gatilhos `errorCaptured`em uma cadeia de herança de um componente ou na cadeia do componente pai, todos eles serão invocados para o mesmo erro.
166
166
167
-
-If the `errorCaptured`hook itself throws an error, both this error and the original captured error are sent to the global`config.errorHandler`.
167
+
-Caso o próprio gatilho `errorCaptured`lance um erro, tanto este erro quanto o que foi capturado originalmente serão enviados ao`config.errorHandler`.
168
168
169
-
-An `errorCaptured`hook can return `false`to prevent the error from propagating further. This is essentially saying "this error has been handled and should be ignored." It will prevent any additional`errorCaptured`hooks or the global `config.errorHandler`from being invoked for this error.
169
+
-Um gatilho `errorCaptured`pode retornar `false`para prevenir que o erro seja propagado, o que basicamente equivale à dizer que "o erro foi tratado e deve ser ignorado". Isso previne que outros gatilhos`errorCaptured`ou que o `config.errorHandler`sejam invocados para o erro.
170
170
171
171
## renderTracked
172
172
173
-
-**Type:**`(e: DebuggerEvent) => void`
173
+
-**Tipo:**`(e: DebuggerEvent) => void`
174
174
175
-
-**Details:**
175
+
-**Detalhes:**
176
176
177
-
Called when virtual DOM re-render is tracked. The hook receives a `debugger event` as an argument. This event tells you what operation tracked the component and the target object and key of that operation.
177
+
Invocado quando a re-renderização do DOM é monitorada. O gatilho recebe um evento de depuração como argumento. Esse evento informa que operação monitorou o componente, o objeto alvo e a chave da operação.
178
178
179
-
-**Usage:**
179
+
-**Uso:**
180
180
181
181
```html
182
182
<divid="app">
183
-
<buttonv-on:click="addToCart">Add to cart</button>
184
-
<p>Cart({{ cart }})</p>
183
+
<buttonv-on:click="addToCart">Adicionar no carrinho</button>
184
+
<p>Carrinho({{ cart }})</p>
185
185
</div>
186
186
```
187
187
@@ -194,7 +194,7 @@ All lifecycle hooks automatically have their `this` context bound to the instanc
194
194
},
195
195
renderTracked({ key, target, type }) {
196
196
console.log({ key, target, type })
197
-
/*This will be logged when component is rendered for the first time:
197
+
/*Isso será exibido quando o componente for renderizado pela primeira vez:
198
198
{
199
199
key: "cart",
200
200
target: {
@@ -216,18 +216,18 @@ All lifecycle hooks automatically have their `this` context bound to the instanc
216
216
217
217
## renderTriggered
218
218
219
-
-**Type:**`(e: DebuggerEvent) => void`
219
+
-**Tipo:**`(e: DebuggerEvent) => void`
220
220
221
-
-**Details:**
221
+
-**Detalhes:**
222
222
223
-
Called when virtual DOM re-render is triggered.Similarly to [`renderTracked`](#rendertracked), receives a `debugger event` as an argument. This event tells you what operation triggered the re-rendering and the target object and key of that operation.
223
+
Invocado quando a re-renderização do DOM é disparada. De forma similar ao [`renderTracked`](#rendertracked), ele recebe um evento de depuração como argumento. Esse evento informa que operação disparou a re-renderização, o objeto alvo e a chave da operação.
224
224
225
225
-**Usage:**
226
226
227
227
```html
228
228
<divid="app">
229
-
<buttonv-on:click="addToCart">Add to cart</button>
230
-
<p>Cart({{ cart }})</p>
229
+
<buttonv-on:click="addToCart">Adicionar no carrinho</button>
230
+
<p>Carrinho({{ cart }})</p>
231
231
</div>
232
232
```
233
233
@@ -244,7 +244,7 @@ All lifecycle hooks automatically have their `this` context bound to the instanc
0 commit comments