CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-vueuse--shared

Collection of essential shared Vue Composition Utilities providing foundational building blocks for reactive Vue applications

Pending
Overview
Eval results
Files

common-utilities.mddocs/

Common Utilities

General purpose utilities including counters, toggles, type conversions, lifecycle helpers, and basic data manipulation functions.

Capabilities

useCounter

Basic counter with increment, decrement, and reset functionality.

/**
 * Basic counter with increment/decrement controls
 * @param initialValue - Initial counter value
 * @param options - Counter options
 * @returns Counter state and controls
 */
function useCounter(initialValue?: number, options?: UseCounterOptions): UseCounterReturn;

interface UseCounterOptions {
  min?: number;
  max?: number;
}

interface UseCounterReturn {
  count: Ref<number>;
  inc: (delta?: number) => number;
  dec: (delta?: number) => number;
  get: () => number;
  set: (value: number) => number;
  reset: (value?: number) => number;
}

Usage Example:

import { useCounter } from "@vueuse/shared";

const { count, inc, dec, set, reset } = useCounter(0, {
  min: 0,
  max: 10
});

console.log(count.value); // 0

inc();        // count: 1
inc(5);       // count: 6
dec(2);       // count: 4
set(8);       // count: 8
reset();      // count: 0 (back to initial)
reset(5);     // count: 5 (reset to specific value)

// Respects min/max bounds
inc(10);      // count: 10 (capped at max)
dec(15);      // count: 0 (capped at min)

useToggle

Boolean state with toggle functionality.

/**
 * Boolean state with toggle function
 * @param initialValue - Initial boolean value
 * @returns Toggle state and controls
 */
function useToggle(initialValue?: boolean): UseToggleReturn;

interface UseToggleReturn {
  0: Ref<boolean>;
  1: (value?: boolean) => boolean;
}

Usage Example:

import { useToggle } from "@vueuse/shared";

const [isVisible, toggle] = useToggle(false);

console.log(isVisible.value); // false

toggle();          // true
toggle();          // false  
toggle(true);      // true (set specific value)
toggle(false);     // false (set specific value)

// Destructuring alternative
const { 0: isOpen, 1: toggleOpen } = useToggle(true);

get

Get the value of a ref, getter, or plain value.

/**
 * Get value of ref/getter/value
 * @param obj - MaybeRefOrGetter to unwrap
 * @returns Unwrapped value
 */
function get<T>(obj: MaybeRefOrGetter<T>): T;

Usage Example:

import { get, ref, computed } from "@vueuse/shared";

const value = ref(42);
const getter = () => 'hello';
const plain = 'world';

console.log(get(value));  // 42
console.log(get(getter)); // 'hello'
console.log(get(plain));  // 'world'

// Useful for generic functions
function processValue<T>(input: MaybeRefOrGetter<T>): T {
  const unwrapped = get(input);
  // Process unwrapped value...
  return unwrapped;
}

set

Set value to a ref or call a setter function.

/**
 * Set value to ref/setter
 * @param ref - Ref or setter function
 * @param value - Value to set
 */
function set<T>(ref: Ref<T> | ((val: T) => void), value: T): void;

Usage Example:

import { set, ref } from "@vueuse/shared";

const count = ref(0);
set(count, 42);
console.log(count.value); // 42

// Works with setter functions too
let localValue = 0;
const setter = (val: number) => { localValue = val; };
set(setter, 100);
console.log(localValue); // 100

isDefined

Type guard to check if a value is defined (not null or undefined).

/**
 * Type guard to check if value is defined
 * @param val - Value to check
 * @returns Type-guarded boolean
 */
function isDefined<T>(val: T): val is NonNullable<T>;

Usage Example:

import { isDefined } from "@vueuse/shared";

const maybeString: string | null | undefined = getValue();

if (isDefined(maybeString)) {
  // TypeScript knows maybeString is string here
  console.log(maybeString.length); // No type error
  console.log(maybeString.toUpperCase()); // No type error
}

// Filter arrays
const values = [1, null, 2, undefined, 3];
const definedValues = values.filter(isDefined); // number[]

makeDestructurable

Make an object both destructurable as object and array.

/**
 * Make object both destructurable as object and array
 * @param obj - Object to make destructurable
 * @param arr - Array representation
 * @returns Object that can be destructured both ways
 */
function makeDestructurable<T extends Record<string, any>, A extends readonly any[]>(
  obj: T, 
  arr: A
): T & A;

Usage Example:

import { makeDestructurable } from "@vueuse/shared";

function usePosition() {
  const x = ref(0);
  const y = ref(0);
  
  return makeDestructurable(
    { x, y }, // Object form
    [x, y]    // Array form
  );
}

const position = usePosition();

// Object destructuring
const { x, y } = position;

// Array destructuring  
const [posX, posY] = position;

// Both x and posX refer to the same ref

until

Promised one-time watch for changes.

/**
 * Promised one-time watch for changes
 * @param r - Source to watch
 * @returns Until chain for conditions
 */
function until<T>(r: MaybeRefOrGetter<T>): UntilToMatch<T, false>;

interface UntilToMatch<T, Not extends boolean> {
  /** Wait for value to be truthy */
  toBeTruthy(): Promise<T>;
  /** Wait for value to be falsy */
  toBeFalsy(): Promise<T>;
  /** Wait for specific value */
  toBe<P = T>(value: MaybeRefOrGetter<P>): Promise<T>;
  /** Wait for value to equal comparison */
  toBeEqual<P = T>(value: MaybeRefOrGetter<P>): Promise<T>;
  /** Wait for custom condition */
  toMatch(condition: (v: T) => boolean): Promise<T>;
  /** Wait for array to contain value */
  toContains(value: any): Promise<T>;
  /** Negate the condition */
  not: UntilToMatch<T, true>;
  /** Change to array matching */
  array: UntilArrayToMatch<T>;
}

Usage Example:

import { until, ref } from "@vueuse/shared";

const count = ref(0);

// Wait for truthy value
await until(count).toBeTruthy();
console.log('Count is now truthy:', count.value);

// Wait for specific value
await until(count).toBe(5);
console.log('Count is now 5');

// Wait for custom condition  
await until(count).toMatch(n => n > 10);
console.log('Count is greater than 10:', count.value);

// Negated conditions
await until(count).not.toBe(0);
console.log('Count is no longer 0');

// With arrays
const items = ref<string[]>([]);
await until(items).toContains('target');
console.log('Items now contains "target"');

Type Conversion Utilities

Reactive utilities for type conversions.

/**
 * Reactive number conversion
 * @param value - Value to convert to number
 * @param options - Conversion options
 * @returns Computed ref with number value
 */
function useToNumber(
  value: MaybeRefOrGetter<number | string>, 
  options?: UseToNumberOptions
): ComputedRef<number>;

interface UseToNumberOptions {
  method?: 'parseFloat' | 'parseInt';
  radix?: number;
  nanToZero?: boolean;
}

/**
 * Reactive string conversion
 * @param value - Value to convert to string
 * @returns Computed ref with string value
 */
function useToString(value: MaybeRefOrGetter<unknown>): ComputedRef<string>;

Usage Examples:

import { useToNumber, useToString, ref } from "@vueuse/shared";

// Number conversion
const input = ref('42.5');
const asNumber = useToNumber(input, { 
  method: 'parseFloat',
  nanToZero: true 
});

console.log(asNumber.value); // 42.5

input.value = 'invalid';
console.log(asNumber.value); // 0 (because nanToZero: true)

// String conversion
const count = ref(42);
const asString = useToString(count);

console.log(asString.value); // '42'

count.value = 100;
console.log(asString.value); // '100'

Date Formatting

Reactive date formatting utility.

/**
 * Reactive date formatting
 * @param date - Date to format
 * @param formatStr - Format string  
 * @param options - Formatting options
 * @returns Computed ref with formatted date string
 */
function useDateFormat(
  date: MaybeRefOrGetter<Date>, 
  formatStr?: MaybeRefOrGetter<string>, 
  options?: UseDateFormatOptions
): ComputedRef<string>;

interface UseDateFormatOptions {
  locales?: MaybeRefOrGetter<string | string[]>;
}

Lifecycle Utilities

Safe versions of Vue lifecycle hooks that work outside component context.

/**
 * Safe version of onBeforeMount
 * @param fn - Function to execute
 * @param sync - Execute synchronously if not in component
 * @returns Whether hook was registered
 */
function tryOnBeforeMount(fn: Fn, sync?: boolean): boolean;

/**
 * Safe version of onMounted
 * @param fn - Function to execute
 * @param sync - Execute synchronously if not in component
 * @returns Whether hook was registered
 */
function tryOnMounted(fn: Fn, sync?: boolean): boolean;

/**
 * Safe version of onBeforeUnmount
 * @param fn - Function to execute
 * @returns Whether hook was registered
 */
function tryOnBeforeUnmount(fn: Fn): boolean;

/**
 * Safe version of onUnmounted
 * @param fn - Function to execute
 * @returns Whether hook was registered
 */
function tryOnUnmounted(fn: Fn): boolean;

/**
 * Safe version of onScopeDispose
 * @param fn - Function to execute
 * @returns Whether hook was registered
 */
function tryOnScopeDispose(fn: Fn): boolean;

Local Injection Utilities

Local fallback versions of provide/inject.

/**
 * Inject with local fallback
 * @param key - Injection key
 * @param defaultValue - Default value if not provided
 * @returns Injected or default value
 */
function injectLocal<T>(key: InjectionKey<T> | string, defaultValue?: T): T;

/**
 * Provide for local injection  
 * @param key - Injection key
 * @param value - Value to provide
 */
function provideLocal<T>(key: InjectionKey<T> | string, value: T): void;

Install with Tessl CLI

npx tessl i tessl/npm-vueuse--shared

docs

array-utilities.md

common-utilities.md

computed-utilities.md

index.md

reactivity.md

ref-utilities.md

state-management.md

time-async.md

utilities.md

watch-utilities.md

tile.json