Anonymous bean (Local Bean)
The class decorated with @Local
is an anonymous bean
, so it is also called a local bean
. This type of bean is only used within the module, there is no naming conflict, and it is easy to define and use
In page component, we created a page component counter
. Now, we pull out the logic of the count
state, put it in a local bean to demonstrate the effect of logic reuse
Create Local Bean: counter
TIP
Context Menu - [Module Path/src/page/counter]: Zova Create/Bean: Local
Enter the name of local bean according to the prompt, such as counter
. The VSCode extension will automatically create the code skeleton of local bean
src/suite/a-demo/modules/demo-basic/src/page/counter/counter.ts
@Local()
export class Counter {}
Local
is a decorator function. The class decorated withLocal
will automatically be registered in the bean container
Add reactive codes
Migrate the code in the page component counter
to the local bean
export class Counter {
count: number = 0;
increment() {
this.count++;
}
decrement() {
this.count--;
}
}
INFO
The property count
defined here is reactive, bidding farewell to the writing style of ref.value
Inject and Use Local Bean
Inject local bean in the page component counter
, and then access properties and methods in render
controller.ts
import { Counter } from './counter.js';
export class ControllerPageCounter {
@Use()
$$counter: Counter;
}
Use
is a decorator function. By the property decorated withUse
, the system will automatically look up or create an instance in the bean container, and then inject it into page component
render.tsx
export class RenderCounter {
render() {
return (
<div>
<div>{this.$$counter.count}</div>
<button onClick={() => this.$$counter.increment()}>Increment</button>
<button onClick={() => this.$$counter.decrement()}>Decrement</button>
</div>
);
}
}