rue_core/component.rs
1use crate::node::VNode;
2
3/// A UI component with lifecycle hooks, similar to Vue 3's Options API.
4///
5/// # Lifecycle
6///
7/// 1. **`init()`** — called once before the first render. Initialize Signals,
8/// Computed values, and Effects here. Equivalent to Vue 3's `setup()` or
9/// the `data()` option.
10///
11/// 2. **`render()`** — called to produce the VNode tree. Called on initial
12/// mount and on every subsequent update. This is the component's template.
13///
14/// 3. **`mounted()`** — called after the component's DOM nodes have been
15/// inserted into the document. Use this to access DOM properties,
16/// integrate with third-party JS libraries, or start timers.
17/// Equivalent to Vue 3's `onMounted()`.
18///
19/// 4. **`should_update()`** — called before each re-render. Return `false`
20/// to skip the update entirely (useful for optimization).
21///
22/// # Example
23///
24/// ```ignore
25/// use rue_core::*;
26/// use rue_macros::html;
27///
28/// struct Counter {
29/// count: Signal<i32>,
30/// }
31///
32/// impl Component for Counter {
33/// fn init(&mut self) {
34/// self.count = signal(0);
35/// }
36///
37/// fn render(&self) -> VNode {
38/// let value = self.count.get_clone();
39/// html! {
40/// <div>
41/// <p>{"Count: "}{value}</p>
42/// <button on:click={move |_| {
43/// self.count.set(self.count.get_clone() + 1);
44/// }}>{"+"}</button>
45/// </div>
46/// }
47/// }
48/// }
49/// ```
50pub trait Component: 'static {
51 /// Initialize component state. Called once before first render.
52 /// Create your Signals, Computed values, and side-effect subscriptions here.
53 fn init(&mut self) {}
54
55 /// Called after the component is mounted to the DOM and the initial
56 /// VNode tree has been rendered. The DOM nodes are accessible via
57 /// [`VNode::dom_node()`] on the tree returned by the first `render()` call.
58 fn mounted(&self) {}
59
60 /// Render the component's UI. Called on mount and on every update.
61 /// Must return a valid [`VNode`] tree.
62 fn render(&self) -> VNode;
63
64 /// Called before each re-render. Return `false` to skip the update.
65 /// Default implementation returns `true`.
66 fn should_update(&self) -> bool {
67 true
68 }
69}