Lifecycle Hooks

All hooks have this bound to the reactive component state.

HookWhen it fires
onBeforeMountBefore the DOM walk begins — $el not yet set
onMountAfter mounting — DOM ready, $el and $refs available
onBeforeUnmountBefore destroy — cleanup event listeners, timers here
onDestroyAfter the component is destroyed
onActivatedWhen a keepAlive component is restored from cache
onDeactivatedWhen a keepAlive component is stored in cache
onErrorCatches errors thrown by descendant onMount hooks

Example — timer with cleanup

JavaScript
{
    data: { ticks: 0 },

    onBeforeMount() {
        // DOM not yet walked — no $el, no $refs
        console.log('before mount');
    },

    onMount() {
        // DOM ready — $el and $refs are available
        this._timer = setInterval(() => this.ticks++, 1000);
        console.log('root element:', this.$el.tagName);
    },

    onBeforeUnmount() {
        // Cleanup before destroy
        clearInterval(this._timer);
    },

    onDestroy() {
        console.log('component destroyed');
    }
}

keepAlive hooks

Set keepAlive: true on a route to cache the component's DOM and state between navigations.

JavaScript
// keepAlive lifecycle
{
    onActivated() {
        // Restored from cache — re-subscribe to live data
        this.startPolling();
    },
    onDeactivated() {
        // Stored in cache — pause background work
        this.stopPolling();
    }
}

Error boundary — onError

An onError hook catches errors thrown by any descendant component's onMount. The error does not propagate further.

JavaScript
// Error boundary — catches errors from descendant onMount
{
    data: { hasError: false, errorMsg: '' },
    onError(err) {
        this.hasError = true;
        this.errorMsg = err.message;
    },
    template: `
        <p cv-if="hasError">Error: {{ errorMsg }}</p>
        <risky-widget cv-if="!hasError" />
    `
}
On the root createApp config, onMount fires after the first route is fully rendered — safe for third-party DOM libraries.
← Reactivity Router →