Component lifecycle

These lifecycle events are executed when mount() API is called on a target element:

Event Description
setup Called after component setup function is executed
dom Called after component template is cloned
element Called once for every node in cloned template
attribute Called for every attribute of an Element node
init Called when a component is visible and ready
change Called when a property has changed
destroy Callend when Custom Element is removed

These hooks can be used inside setup functions or inside reusable code factories.

Example 1: ready triggers once, count triggers every time a prop changes.

<template>
<div>
Ready? {{ready}}<br />
Update count: {{count}}
</div>

<script setup>
import { onInit, shallowRef, defineProp } from '@li3/web';

export default function () {
const trigger = defineProp('trigger');
const ready = shallowRef(false);
const count = shallowRef(0);

onInit(function () {
ready.value = true;
});

onUpdate(function () {
count.value++;
});
}
</script>
</template>

Example 2: reusable code with hooks.

<template component="app-scroller">
<div>Scroll position: {{ scroll.y }}</div>

<script setup>
import { onInit, onDestroy, ref, debounce } from '@li3/web';

// this could be moved to use-scroll.js
export function useWindowScroll() {
const ref = ref(0);
const handler = debounce(handler(e) => ref.value = { x: window.scrollX, y: window.scrollY });

onInit(() => window.addEventListener('scroll', handler));
onDestroy(() => window.removeEventListener('scroll', handler));

return ref;
}

export default function () {
const scroll = useWindowScroll();
return { scroll };
}
</script>
</template>

<template app>
<app-scroller></app-scroller>
</template>

Mounts a component into a target element. Can be used to programatically create DOM structures with the same semantics as a custom element. In fact, this is the same API called by a custom element create with Lithium.

Target can be a string with a CSS selector, an HTML element or a DocumentFragment.

component is a component definition object, with any of:

  • a template string or element
  • a setup function
  • a shadowDom configuration.