Skip to content

Lifecycle

Sometimes, you want to execute code only when a Van Element has connected to the DOM. The most typical use case is when you try to access assignedElements from a slot:

ts
define("connect-example", () => {
  const dom = slot();
  return div(dom, pre("Items in slot - ", dom.assignedElements().length));
});
html
<connect-example><p>I am in the slot</p></connect-example>
Result

I am in the slot

Here, the number of items in the slot is 0 🤔 that is because slots will only get populated after the Web Component has mounted.

mount

Fortunately, we can define a mount callback:

ts
define("mount-showcase", ({ mount }) => {
  const dom = slot();
  const slotCount = van.state(dom.assignedElements().length);
  mount(() => {
    slotCount.val = dom.assignedElements().length;
  });
  return div(dom, pre("Items in slot - ", slotCount));
});
html
<mount-showcase><p>I am in the slot</p></mount-showcase>
Result

I am in the slot

dismount

The mount function can return another callback that triggers when the component is dismounted.

js
mount(() => {
  console.log("mounted");
  return () => console.log("dismounted");
});

This can be useful for unsubscribing to certain events, keeping tracks of mounted elements, etc.

Note

In most cases, you won't have to use mount. However, there are cases where you need it and it will then be very useful!