CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-vue--runtime-core

Vue.js 3 runtime core library providing foundational APIs for building custom renderers and managing reactive component systems

Pending
Overview
Eval results
Files

lifecycle.mddocs/

Lifecycle Hooks

Vue's lifecycle hooks provide a way to execute code at specific stages of a component's lifecycle. These hooks are available in both the Composition API and Options API.

Capabilities

Mount & Unmount Hooks

Hooks for component mounting and unmounting phases.

/**
 * Registers a callback to be called before the component is mounted
 * @param hook - Callback function to execute
 */
function onBeforeMount(hook: () => void): void;

/**
 * Registers a callback to be called after the component is mounted
 * @param hook - Callback function to execute
 */
function onMounted(hook: () => void): void;

/**
 * Registers a callback to be called before the component is unmounted
 * @param hook - Callback function to execute
 */
function onBeforeUnmount(hook: () => void): void;

/**
 * Registers a callback to be called after the component is unmounted
 * @param hook - Callback function to execute
 */
function onUnmounted(hook: () => void): void;

Usage Examples:

import { defineComponent, ref, onBeforeMount, onMounted, onBeforeUnmount, onUnmounted } from "@vue/runtime-core";

const MyComponent = defineComponent({
  setup() {
    const data = ref(null);
    let timer: NodeJS.Timeout;
    
    onBeforeMount(() => {
      console.log("Component is about to be mounted");
      // Good place to prepare data or setup that doesn't require DOM
    });
    
    onMounted(() => {
      console.log("Component has been mounted to DOM");
      // DOM is available, good for:
      // - Accessing DOM elements
      // - Setting up timers
      // - Initializing third-party libraries
      
      timer = setInterval(() => {
        console.log("Timer tick");
      }, 1000);
    });
    
    onBeforeUnmount(() => {
      console.log("Component is about to be unmounted");
      // Clean up before unmount
      if (timer) {
        clearInterval(timer);
      }
    });
    
    onUnmounted(() => {
      console.log("Component has been unmounted");
      // Final cleanup
      data.value = null;
    });
    
    return { data };
  }
});

Update Hooks

Hooks for component update phases when reactive data changes.

/**
 * Registers a callback to be called before the component updates
 * @param hook - Callback function to execute
 */
function onBeforeUpdate(hook: () => void): void;

/**
 * Registers a callback to be called after the component updates
 * @param hook - Callback function to execute
 */
function onUpdated(hook: () => void): void;

Usage Examples:

import { defineComponent, ref, onBeforeUpdate, onUpdated } from "@vue/runtime-core";

const UpdateComponent = defineComponent({
  setup() {
    const count = ref(0);
    const prevCount = ref(0);
    
    onBeforeUpdate(() => {
      console.log("Component is about to update");
      // Capture current state before update
      prevCount.value = count.value;
    });
    
    onUpdated(() => {
      console.log(`Component updated: ${prevCount.value} -> ${count.value}`);
      // DOM has been updated
      // Good place to:
      // - Access updated DOM elements
      // - Perform side effects based on new data
    });
    
    const increment = () => {
      count.value++;
    };
    
    return {
      count,
      increment
    };
  }
});

KeepAlive Hooks

Special hooks for components wrapped in <KeepAlive>.

/**
 * Registers a callback to be called when a kept-alive component is activated
 * @param hook - Callback function to execute
 */
function onActivated(hook: () => void): void;

/**
 * Registers a callback to be called when a kept-alive component is deactivated
 * @param hook - Callback function to execute
 */
function onDeactivated(hook: () => void): void;

Usage Examples:

import { defineComponent, ref, onActivated, onDeactivated, onMounted, onUnmounted } from "@vue/runtime-core";

const KeepAliveComponent = defineComponent({
  setup() {
    const isActive = ref(false);
    let timer: NodeJS.Timeout;
    
    onMounted(() => {
      console.log("Component mounted (first time only)");
    });
    
    onActivated(() => {
      console.log("Component activated (every time it becomes visible)");
      isActive.value = true;
      
      // Resume operations when component becomes active
      timer = setInterval(() => {
        console.log("Active component timer");
      }, 1000);
    });
    
    onDeactivated(() => {
      console.log("Component deactivated (every time it becomes hidden)");
      isActive.value = false;
      
      // Pause operations when component becomes inactive
      if (timer) {
        clearInterval(timer);
      }
    });
    
    onUnmounted(() => {
      console.log("Component unmounted (only when KeepAlive is destroyed)");
    });
    
    return { isActive };
  }
});

Debug Hooks

Development-only hooks for debugging render performance.

/**
 * Registers a callback to be called when reactive dependencies are tracked during render
 * @param hook - Debug callback with dependency information
 */
function onRenderTracked(hook: DebuggerHook): void;

/**
 * Registers a callback to be called when reactive dependencies trigger a re-render
 * @param hook - Debug callback with trigger information
 */
function onRenderTriggered(hook: DebuggerHook): void;

type DebuggerHook = (e: DebuggerEvent) => void;

interface DebuggerEvent {
  effect: ReactiveEffect;
  target: object;
  type: TrackOpTypes | TriggerOpTypes;
  key: any;
  newValue?: any;
  oldValue?: any;
}

Usage Examples:

import { defineComponent, ref, onRenderTracked, onRenderTriggered } from "@vue/runtime-core";

const DebugComponent = defineComponent({
  setup() {
    const count = ref(0);
    const name = ref("Vue");
    
    onRenderTracked((e) => {
      console.log("Dependency tracked during render:", {
        target: e.target,
        key: e.key,
        type: e.type
      });
    });
    
    onRenderTriggered((e) => {
      console.log("Re-render triggered by:", {
        target: e.target,
        key: e.key,
        type: e.type,
        oldValue: e.oldValue,
        newValue: e.newValue
      });
    });
    
    return {
      count,
      name,
      increment: () => count.value++,
      updateName: (newName: string) => name.value = newName
    };
  }
});

Error Handling Hook

Hook for catching errors in descendant components.

/**
 * Registers a callback to be called when an error is captured from a descendant component
 * @param hook - Error handler callback
 */
function onErrorCaptured(hook: ErrorCapturedHook): void;

type ErrorCapturedHook = (
  err: unknown,
  instance: ComponentInternalInstance | null,
  info: string
) => boolean | void;

Usage Examples:

import { defineComponent, onErrorCaptured } from "@vue/runtime-core";

const ErrorBoundaryComponent = defineComponent({
  setup() {
    const errorMessages = ref<string[]>([]);
    
    onErrorCaptured((error, instance, info) => {
      console.error("Error captured:", error);
      console.log("Error info:", info);
      console.log("Component instance:", instance);
      
      errorMessages.value.push(`${error}: ${info}`);
      
      // Return false to prevent the error from propagating further
      return false;
    });
    
    return {
      errorMessages
    };
  }
});

Server-Side Rendering Hook

Hook for server-side rendering data prefetching.

/**
 * Registers a callback to be called during server-side rendering for data prefetching
 * @param hook - Async callback for data prefetching
 */
function onServerPrefetch(hook: () => Promise<any>): void;

Usage Examples:

import { defineComponent, ref, onServerPrefetch, onMounted } from "@vue/runtime-core";

const SSRComponent = defineComponent({
  setup() {
    const data = ref(null);
    const loading = ref(true);
    
    const fetchData = async () => {
      // Simulate API call
      const response = await fetch('/api/data');
      data.value = await response.json();
      loading.value = false;
    };
    
    onServerPrefetch(async () => {
      // This runs only on the server during SSR
      await fetchData();
      console.log("Data prefetched on server");
    });
    
    onMounted(() => {
      // This runs only on the client
      if (data.value === null) {
        // Data wasn't prefetched (client-only rendering)
        fetchData();
      }
    });
    
    return {
      data,
      loading
    };
  }
});

Lifecycle Execution Order

The lifecycle hooks execute in the following order:

Component Creation & Mounting

  1. setup() - Composition API setup
  2. onBeforeMount() - Before DOM mounting
  3. onMounted() - After DOM mounting

Component Updates

  1. onBeforeUpdate() - Before re-render
  2. onUpdated() - After re-render and DOM update

Component KeepAlive (if applicable)

  1. onActivated() - When component becomes active
  2. onDeactivated() - When component becomes inactive

Component Unmounting

  1. onBeforeUnmount() - Before unmounting
  2. onUnmounted() - After unmounting

Error Handling (when errors occur)

  1. onErrorCaptured() - When descendant error is captured

SSR (server-side only)

  1. onServerPrefetch() - During server-side rendering

Usage Notes

  • All lifecycle hooks must be called synchronously during the component's setup phase
  • Hooks can be called multiple times to register multiple callbacks
  • Hooks are automatically bound to the current component instance
  • In SSR, only onServerPrefetch runs on the server; others run on the client during hydration
  • onRenderTracked and onRenderTriggered only work in development mode
  • onActivated and onDeactivated only work for components wrapped in <KeepAlive>

Install with Tessl CLI

npx tessl i tessl/npm-vue--runtime-core

docs

asset-resolution.md

builtin-components.md

components.md

composition-helpers.md

dependency-injection.md

error-handling.md

hydration.md

index.md

internal-render-helpers.md

lifecycle.md

reactivity.md

scheduler-timing.md

ssr-context.md

vdom-rendering.md

watch-effects.md

tile.json