CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-vueuse--core

Collection of essential Vue Composition Utilities providing 146+ reactive composable functions for Vue 3 applications

Pending
Overview
Eval results
Files

template-composition.mddocs/

Template Composition

Advanced template composition utilities for creating reusable templates, template-based promises, and template reference helpers. These utilities enable sophisticated template patterns and component composition strategies.

Capabilities

Template Reusability

createReusableTemplate

Create reusable template components that can be defined once and reused multiple times.

/**
 * Create a pair of components for defining and reusing templates
 * @param options - Template configuration options
 * @returns Template component pair with define and reuse components
 */
function createReusableTemplate<
  Bindings extends Record<string, any> = {},
  Props extends Record<string, any> = {},
  MapSlotNameToSlotProps extends Record<string, any> = {}
>(
  options?: CreateReusableTemplateOptions<Props>
): ReusableTemplatePair<Bindings, MapSlotNameToSlotProps>;

interface CreateReusableTemplateOptions<Props extends Record<string, any>> {
  inheritAttrs?: boolean;
  props?: ComponentObjectPropsOptions<Props>;
}

type ReusableTemplatePair<
  Bindings extends Record<string, any>,
  MapSlotNameToSlotProps extends Record<string, any>
> = [
  DefineTemplateComponent<Bindings, MapSlotNameToSlotProps>,
  ReuseTemplateComponent<Bindings, MapSlotNameToSlotProps>
] & {
  define: DefineTemplateComponent<Bindings, MapSlotNameToSlotProps>;
  reuse: ReuseTemplateComponent<Bindings, MapSlotNameToSlotProps>;
};

Usage Examples:

import { createReusableTemplate } from "@vueuse/core";

// Create template pair
const [DefineTemplate, ReuseTemplate] = createReusableTemplate<{ name: string }>();

// In your component template:
// <DefineTemplate v-slot="{ name }">
//   <h1>Hello {{ name }}!</h1>
// </DefineTemplate>
//
// <ReuseTemplate name="World" />
// <ReuseTemplate name="Vue" />

createTemplatePromise

Create Promise-based templates for modal dialogs, confirmations, and async interactions.

/**
 * Create Promise-based template components for modal interactions
 * @param options - Template promise configuration options
 * @returns Template promise component and utilities
 */
function createTemplatePromise<Return = any, Args extends any[] = []>(
  options?: TemplatePromiseOptions
): TemplatePromiseReturn<Return, Args>;

interface TemplatePromiseReturn<Return, Args extends any[]> {
  TemplatePromise: DefineComponent<TemplatePromiseProps<Return, Args>>;
  start: (...args: Args) => Promise<Return>;
  close: () => void;
}

interface TemplatePromiseProps<Return, Args extends any[]> {
  promise: Promise<Return> | undefined;
  resolve: (v: Return | Promise<Return>) => void;
  reject: (v: any) => void;
  args: Args;
  isResolving: boolean;
  options: TemplatePromiseOptions;
}

interface TemplatePromiseOptions {
  singleton?: boolean;
  transition?: TransitionGroupProps;
}

Usage Examples:

import { createTemplatePromise } from "@vueuse/core";

// Create confirmation dialog
const { TemplatePromise, start } = createTemplatePromise<boolean>();

// Use in template:
// <TemplatePromise v-slot="{ resolve, reject, args }">
//   <div class="modal">
//     <p>Are you sure?</p>
//     <button @click="resolve(true)">Yes</button>
//     <button @click="resolve(false)">No</button>
//   </div>
// </TemplatePromise>

// Trigger programmatically
const confirmed = await start();

Template References

templateRef

Template reference helper with type safety and automatic cleanup.

/**
 * Type-safe template reference helper
 * @param key - Template ref key or element selector
 * @param initialValue - Initial ref value
 * @returns Template ref with enhanced capabilities
 */
function templateRef<T extends Element | ComponentPublicInstance = Element>(
  key?: string | number | symbol,
  initialValue?: T | null
): Readonly<Ref<T | null>>;

Usage Examples:

import { templateRef } from "@vueuse/core";

// In setup
const buttonRef = templateRef<HTMLButtonElement>('button');

// In template: <button ref="button">Click me</button>

// Access element
console.log(buttonRef.value?.textContent);

useTemplateRefsList

Manage multiple template references with reactive list support.

/**
 * Reactive template references list for v-for scenarios
 * @returns Template refs list with reactive updates
 */
function useTemplateRefsList<T = Element>(): [
  Ref<T[]>,
  (el: T | ComponentPublicInstance | Element | null) => void
];

Usage Examples:

import { useTemplateRefsList } from "@vueuse/core";

// In setup
const [itemRefs, setItemRef] = useTemplateRefsList<HTMLDivElement>();

// In template:
// <div v-for="item in items" :key="item.id" :ref="setItemRef">
//   {{ item.name }}
// </div>

// Access elements
itemRefs.value.forEach(el => console.log(el.textContent));

Function Utilities

createUnrefFn

Create functions that automatically unref their arguments.

/**
 * Create a function that automatically unrefs its arguments
 * @param fn - Function to enhance with auto-unref
 * @returns Function that accepts refs and automatically unrefs them
 */
function createUnrefFn<T extends AnyFn>(fn: T): UnrefFnReturn<T>;

type UnrefFnReturn<T extends AnyFn> = (
  ...args: ToRefs<Parameters<T>>
) => ReturnType<T>;

Usage Examples:

import { createUnrefFn, ref } from "@vueuse/core";

// Create unref function
const add = createUnrefFn((a: number, b: number) => a + b);

// Use with refs
const x = ref(1);
const y = ref(2);
const result = add(x, y); // Automatically unrefs x and y

unrefElement

Unref element from template refs, component instances, or plain elements.

/**
 * Unref element from various ref types
 * @param elRef - Element reference (ref, component, or element)
 * @returns Unrefed HTML element or null
 */
function unrefElement<T extends MaybeElement>(
  elRef: MaybeElementRef<T>
): UnwrapNestedRefs<T>;

type MaybeElement = HTMLElement | SVGElement | VueInstance | undefined | null;
type MaybeElementRef<T extends MaybeElement = MaybeElement> = MaybeRef<T>;

Usage Examples:

import { unrefElement, ref } from "@vueuse/core";

const elementRef = ref<HTMLDivElement>();
const componentRef = ref<ComponentPublicInstance>();

// Unref to get actual DOM element
const element = unrefElement(elementRef);
const componentElement = unrefElement(componentRef); // Gets component.$el

Reactive Composition

computedInject

Computed with dependency injection support.

/**
 * Computed with dependency injection from parent components
 * @param key - Injection key
 * @param fn - Computation function receiving injected value
 * @param defaultValue - Default value if injection fails
 * @returns Computed ref with injected dependency
 */
function computedInject<T, K>(
  key: InjectionKey<T> | string,
  fn: (source: T, oldValue: K | undefined) => K,
  defaultValue?: T
): ComputedRef<K>;

Usage Examples:

import { computedInject, provide, ref } from "@vueuse/core";

// Parent provides theme
const theme = ref('dark');
provide('theme', theme);

// Child computes based on injected theme
const computedStyles = computedInject('theme', (theme) => ({
  background: theme === 'dark' ? '#000' : '#fff',
  color: theme === 'dark' ? '#fff' : '#000'
}));

Event Management

createEventHook

Create custom event hooks for component communication.

/**
 * Create custom event hook for component events
 * @returns Event hook with trigger and on methods
 */
function createEventHook<T = any>(): EventHook<T>;

interface EventHook<T = any> {
  on: (fn: (param: T) => void) => void;
  off: (fn: (param: T) => void) => void;
  trigger: (param: T) => Promise<unknown[]>;
}

Usage Examples:

import { createEventHook } from "@vueuse/core";

// Create custom event
const onDataLoaded = createEventHook<{ data: any[] }>();

// Listen to event
onDataLoaded.on(({ data }) => {
  console.log('Data loaded:', data);
});

// Trigger event
onDataLoaded.trigger({ data: [1, 2, 3] });

Shared Types

// Component types
type VueInstance = ComponentPublicInstance;
type MaybeElement = HTMLElement | SVGElement | VueInstance | undefined | null;
type MaybeElementRef<T extends MaybeElement = MaybeElement> = MaybeRef<T>;

// Template component types
type DefineTemplateComponent<
  Bindings extends Record<string, any>,
  MapSlotNameToSlotProps extends Record<string, any>
> = DefineComponent & {
  new(): { 
    $slots: { 
      default: (_: Bindings & { 
        $slots: GenerateSlotsFromSlotMap<MapSlotNameToSlotProps> 
      }) => any 
    } 
  }
};

type ReuseTemplateComponent<
  Bindings extends Record<string, any>,
  MapSlotNameToSlotProps extends Record<string, any>
> = DefineComponent<Bindings> & {
  new(): { 
    $slots: GenerateSlotsFromSlotMap<MapSlotNameToSlotProps> 
  }
};

// Function utility types
type AnyFn = (...args: any[]) => any;
type ToRefs<T extends readonly unknown[]> = {
  [K in keyof T]: MaybeRef<T[K]>
};

type UnrefFnReturn<T extends AnyFn> = (
  ...args: ToRefs<Parameters<T>>
) => ReturnType<T>;

// Event hook types
interface EventHookOn<T = any> {
  (fn: (param: T) => void): void;
}

interface EventHookOff<T = any> {
  (fn: (param: T) => void): void;
}

interface EventHookTrigger<T = any> {
  (param: T): Promise<unknown[]>;
}

Install with Tessl CLI

npx tessl i tessl/npm-vueuse--core

docs

animation-effects.md

browser-apis.md

device-sensors.md

dom-elements.md

events.md

index.md

mouse-pointer.md

network.md

shared-utilities.md

state-management.md

template-composition.md

utilities.md

tile.json