mirror of
https://github.com/odoo/owl.git
synced 2025-10-06 19:59:41 +07:00
[IMP] component: add setup lifecycle hook
This commit is contained in:
@@ -11,6 +11,7 @@
|
||||
- [Methods](#methods)
|
||||
- [Lifecycle](#lifecycle)
|
||||
- [`constructor(parent, props)`](#constructorparent-props)
|
||||
- [`setup()`](#setup)
|
||||
- [`willStart()`](#willstart)
|
||||
- [`mounted()`](#mounted)
|
||||
- [`willUpdateProps(nextProps)`](#willupdatepropsnextprops)
|
||||
@@ -324,7 +325,7 @@ a owl component:
|
||||
|
||||
| Method | Description |
|
||||
| ------------------------------------------------ | ----------------------------------------------------------- |
|
||||
| **[constructor](#constructorparent-props)** | constructor |
|
||||
| **[setup](#setup)** | setup |
|
||||
| **[willStart](#willstart)** | async, before first rendering |
|
||||
| **[mounted](#mounted)** | just after component is rendered and added to the DOM |
|
||||
| **[willUpdateProps](#willupdatepropsnextprops)** | async, before props update |
|
||||
@@ -369,6 +370,23 @@ class ClickCounter extends owl.Component {
|
||||
}
|
||||
```
|
||||
|
||||
Hook functions can be called in the constructor.
|
||||
|
||||
#### `setup()`
|
||||
|
||||
_setup_ is run just after the component is constructed. It is a lifecycle method,
|
||||
very similar to the _constructor_, except that it does not receive any argument.
|
||||
|
||||
It is a valid method to call hook functions. Note that one of the main reason to
|
||||
have the `setup` hook in the component lifecycle is to make it possible to
|
||||
monkey patch it. It is a common need in the Odoo ecosystem.
|
||||
|
||||
```javascript
|
||||
setup() {
|
||||
useSetupAutofocus();
|
||||
}
|
||||
```
|
||||
|
||||
#### `willStart()`
|
||||
|
||||
willStart is an asynchronous hook that can be implemented to
|
||||
|
||||
@@ -131,7 +131,7 @@ class SomeComponent extends Component {
|
||||
### One rule
|
||||
|
||||
There is only one rule: every hook for a component has to be called in the
|
||||
constructor (or in class fields):
|
||||
constructor, in the _setup_ method, or in class fields:
|
||||
|
||||
```js
|
||||
// ok
|
||||
@@ -147,6 +147,13 @@ class SomeComponent extends Component {
|
||||
}
|
||||
}
|
||||
|
||||
// also ok
|
||||
class SomeComponent extends Component {
|
||||
setup() {
|
||||
this.state = useState({ value: 0 });
|
||||
}
|
||||
}
|
||||
|
||||
// not ok: this is executed after the constructor is called
|
||||
class SomeComponent extends Component {
|
||||
async willStart() {
|
||||
|
||||
Reference in New Issue
Block a user