CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-vue--composition-api

Provides Vue 3 Composition API compatibility for Vue 2 applications with reactive state management and lifecycle hooks.

Pending
Overview
Eval results
Files

lifecycle.mddocs/

Lifecycle Hooks

Function-based lifecycle hooks that integrate with Vue 2's component lifecycle system. These hooks allow you to execute code at specific points in the component lifecycle within the setup function.

Capabilities

Basic Lifecycle Hooks

Core lifecycle hooks that correspond to Vue 2's component lifecycle options.

/**
 * Registers a callback to be called before the component is mounted
 * @param hook - Callback function to execute
 * @param target - Target component instance (optional)
 * @returns Cleanup function or undefined
 */
function onBeforeMount(hook: () => void, target?: ComponentInternalInstance): Function | undefined;

/**
 * Registers a callback to be called after the component is mounted
 * @param hook - Callback function to execute
 * @param target - Target component instance (optional)
 * @returns Cleanup function or undefined
 */
function onMounted(hook: () => void, target?: ComponentInternalInstance): Function | undefined;

/**
 * Registers a callback to be called before the component updates
 * @param hook - Callback function to execute
 * @param target - Target component instance (optional)
 * @returns Cleanup function or undefined  
 */
function onBeforeUpdate(hook: () => void, target?: ComponentInternalInstance): Function | undefined;

/**
 * Registers a callback to be called after the component updates
 * @param hook - Callback function to execute
 * @param target - Target component instance (optional)
 * @returns Cleanup function or undefined
 */
function onUpdated(hook: () => void, target?: ComponentInternalInstance): Function | undefined;

/**
 * Registers a callback to be called before the component is unmounted
 * @param hook - Callback function to execute
 * @param target - Target component instance (optional)
 * @returns Cleanup function or undefined
 */
function onBeforeUnmount(hook: () => void, target?: ComponentInternalInstance): Function | undefined;

/**
 * Registers a callback to be called after the component is unmounted
 * @param hook - Callback function to execute
 * @param target - Target component instance (optional)
 * @returns Cleanup function or undefined
 */
function onUnmounted(hook: () => void, target?: ComponentInternalInstance): Function | undefined;

Usage Examples:

import { 
  ref, 
  onBeforeMount, 
  onMounted, 
  onBeforeUpdate, 
  onUpdated, 
  onBeforeUnmount, 
  onUnmounted 
} from "@vue/composition-api";

export default {
  setup() {
    const count = ref(0);
    const element = ref<HTMLElement | null>(null);
    
    onBeforeMount(() => {
      console.log("Component is about to be mounted");
      // DOM is not available yet
    });
    
    onMounted(() => {
      console.log("Component has been mounted");
      // DOM is available
      if (element.value) {
        element.value.focus();
      }
    });
    
    onBeforeUpdate(() => {
      console.log("Component is about to update");
      // DOM still reflects old values
    });
    
    onUpdated(() => {
      console.log("Component has been updated");
      // DOM reflects new values
    });
    
    onBeforeUnmount(() => {
      console.log("Component is about to be unmounted");
      // Cleanup subscriptions, timers, etc.
    });
    
    onUnmounted(() => {
      console.log("Component has been unmounted");
      // Final cleanup
    });
    
    return {
      count,
      element,
    };
  },
};

Error Handling Hook

Hook for capturing and handling errors in child components.

/**
 * Registers a callback to be called when an error is captured from a child component
 * @param hook - Error handling callback
 */
function onErrorCaptured(
  hook: (error: Error, instance: ComponentInstance, info: string) => boolean | void,
  target?: ComponentInternalInstance
): Function | undefined;

Usage Examples:

import { onErrorCaptured } from "@vue/composition-api";

export default {
  setup() {
    onErrorCaptured((error, instance, info) => {
      console.error("Error captured:", error);
      console.log("Error info:", info);
      console.log("Component instance:", instance);
      
      // Return false to prevent the error from propagating further
      return false;
    });
    
    return {};
  },
};

Keep-Alive Hooks

Hooks for components wrapped in keep-alive, handling activation and deactivation.

/**
 * Registers a callback to be called when a kept-alive component is activated
 * @param hook - Callback function to execute
 * @param target - Target component instance (optional)
 * @returns Cleanup function or undefined
 */
function onActivated(hook: () => void, target?: ComponentInternalInstance): Function | undefined;

/**
 * Registers a callback to be called when a kept-alive component is deactivated
 * @param hook - Callback function to execute
 * @param target - Target component instance (optional)
 * @returns Cleanup function or undefined
 */
function onDeactivated(hook: () => void, target?: ComponentInternalInstance): Function | undefined;

Usage Examples:

import { ref, onActivated, onDeactivated } from "@vue/composition-api";

export default {
  setup() {
    const isActive = ref(false);
    
    onActivated(() => {
      console.log("Component activated");
      isActive.value = true;
      // Resume timers, subscriptions, etc.
    });
    
    onDeactivated(() => {
      console.log("Component deactivated");
      isActive.value = false;
      // Pause timers, subscriptions, etc.
    });
    
    return {
      isActive,
    };
  },
};

Server-Side Rendering Hook

Hook for server-side rendering operations that need to be performed before the component is rendered.

/**
 * Registers a callback to be called during server-side rendering
 * @param hook - Async callback function for server prefetch operations
 */
function onServerPrefetch(hook: () => Promise<any> | void, target?: ComponentInternalInstance): Function | undefined;

Usage Examples:

import { ref, onServerPrefetch } from "@vue/composition-api";

export default {
  setup() {
    const data = ref(null);
    
    onServerPrefetch(async () => {
      // This runs only on the server during SSR
      console.log("Prefetching data on server");
      
      try {
        const response = await fetch("/api/initial-data");
        data.value = await response.json();
      } catch (error) {
        console.error("Failed to prefetch data:", error);
      }
    });
    
    return {
      data,
    };
  },
};

Advanced Lifecycle Patterns

Complex patterns for lifecycle management including cleanup, async operations, and resource management.

Resource Management:

import { ref, onMounted, onBeforeUnmount } from "@vue/composition-api";

export default {
  setup() {
    const websocket = ref<WebSocket | null>(null);
    const isConnected = ref(false);
    
    onMounted(() => {
      // Initialize WebSocket connection
      websocket.value = new WebSocket("wss://api.example.com/socket");
      
      websocket.value.onopen = () => {
        isConnected.value = true;
        console.log("WebSocket connected");
      };
      
      websocket.value.onmessage = (event) => {
        console.log("Received message:", event.data);
      };
      
      websocket.value.onclose = () => {
        isConnected.value = false;
        console.log("WebSocket disconnected");
      };
    });
    
    onBeforeUnmount(() => {
      // Clean up WebSocket connection
      if (websocket.value) {
        websocket.value.close();
        websocket.value = null;
      }
    });
    
    return {
      isConnected,
    };
  },
};

Timer Management:

import { ref, onMounted, onBeforeUnmount } from "@vue/composition-api";

export default {
  setup() {
    const time = ref(new Date());
    let timer: NodeJS.Timeout | null = null;
    
    onMounted(() => {
      // Start timer
      timer = setInterval(() => {
        time.value = new Date();
      }, 1000);
    });
    
    onBeforeUnmount(() => {
      // Clean up timer
      if (timer) {
        clearInterval(timer);
        timer = null;
      }
    });
    
    return {
      time,
    };
  },
};

Event Listener Management:

import { ref, onMounted, onBeforeUnmount } from "@vue/composition-api";

export default {
  setup() {
    const windowWidth = ref(window.innerWidth);
    
    const handleResize = () => {
      windowWidth.value = window.innerWidth;
    };
    
    onMounted(() => {
      window.addEventListener("resize", handleResize);
    });
    
    onBeforeUnmount(() => {
      window.removeEventListener("resize", handleResize);
    });
    
    return {
      windowWidth,
    };
  },
};

Async Data Loading:

import { ref, onMounted } from "@vue/composition-api";

export default {
  setup() {
    const data = ref(null);
    const loading = ref(false);
    const error = ref(null);
    
    onMounted(async () => {
      loading.value = true;
      error.value = null;
      
      try {
        const response = await fetch("/api/data");
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        data.value = await response.json();
      } catch (err) {
        error.value = err;
        console.error("Failed to load data:", err);
      } finally {
        loading.value = false;
      }
    });
    
    return {
      data,
      loading,
      error,
    };
  },
};

Multiple Hook Registration

You can register multiple callbacks for the same lifecycle hook, and they will be called in the order they were registered.

import { ref, onMounted, onBeforeUnmount } from "@vue/composition-api";

export default {
  setup() {
    const analytics = ref(null);
    const metrics = ref(null);
    
    // First onMounted callback
    onMounted(() => {
      console.log("Initializing analytics");
      analytics.value = initializeAnalytics();
    });
    
    // Second onMounted callback
    onMounted(() => {
      console.log("Starting metrics collection");
      metrics.value = startMetrics();
    });
    
    // Multiple cleanup callbacks
    onBeforeUnmount(() => {
      if (analytics.value) {
        analytics.value.shutdown();
      }
    });
    
    onBeforeUnmount(() => {
      if (metrics.value) {
        metrics.value.stop();
      }
    });
    
    return {
      analytics,
      metrics,
    };
  },
};

Types

type ComponentInstance = any; // Vue 2 component instance

interface LifecycleHook {
  (hook: Function, target?: ComponentInternalInstance | null): Function | undefined;
}

interface ComponentInternalInstance {
  proxy: ComponentInstance | null;
  setupState: Record<string, any>;
  ctx: Record<string, any>;
  scope: EffectScope;
}

Install with Tessl CLI

npx tessl i tessl/npm-vue--composition-api

docs

advanced-features.md

component-utilities.md

computed.md

dependency-injection.md

index.md

lifecycle.md

reactive-state.md

types.md

watchers.md

tile.json