Skip to content

Vue 3 helpers API

useEmits Events

Builds reactive Vue event handlers.

Signature

ts
export function useEmits<Emits extends EmitsOptions>(
	emits: Emits,
	emit: (...arguments_: never[]) => unknown,
	ignoredEvents: readonly (keyof Emits)[] = []
): ComputedRef<Partial<EmitHandlers<Emits>>>;

Example

ts
import { useEmits } from "@fast-china/utils";

const result = useEmits({ change: null }, () => undefined);

Input

InputTypeRequired / defaultDescription
emitsEmitsRequiredVue emits configuration object.
emit(...arguments_: never[]) => unknownRequiredEmit function provided by the setup context.
ignoredEventsreadonly (keyof Emits)[]Optional; defaults to []Event names not to forward to the child component.

Returns

ValueTypeDescription
resultComputedRef<Partial<EmitHandlers<Emits>>>Event-handler object recomputed with the configuration.

useExpose Expose

Exposes component instance capabilities and returns the same object, allowing setup to return state for Vue Devtools.

Signature

ts
export function useExpose<Exposed extends object>(expose: (exposed?: Exposed) => void, exposed: Exposed): Exposed;

Example

ts
import { useExpose } from "@fast-china/utils";

const exposed = { focus: () => undefined };
const result = useExpose((value) => console.log(value), exposed);

Input

InputTypeRequired / defaultDescription
expose(exposed?: Exposed) => voidRequiredExpose function provided by the setup context.
exposedExposedRequiredState and methods to expose.

Returns

ValueTypeDescription
resultExposedOriginal exposed object.

callOptionalFunction Invoke

Executes a synchronous or asynchronous function, propagating exceptions unchanged.

Signature

ts
export async function callOptionalFunction<Arguments extends readonly unknown[], Result>(
	function_: AwaitableFunction<Arguments, Result> | null | undefined,
	...arguments_: Arguments
): Promise<Awaited<Result> | undefined>;

Example

ts
import { callOptionalFunction } from "@fast-china/utils";

const result = await callOptionalFunction((value: string) => value.length, "Fast");

Input

InputTypeRequired / defaultDescription
function_AwaitableFunction<Arguments, Result> | null | undefinedRequiredOptional function to execute.
arguments_ArgumentsRequiredArguments forwarded unchanged.

Returns

ValueTypeDescription
resultPromise<Awaited<Result> | undefined>Function result, or undefined when no function is supplied.

withInstall Install

Adds Vue 3 app.use() installation support to a main component.

Signature

ts
export function withInstall<Main extends VueInstallValue, Extras extends Record<string, VueInstallValue> = Record<never, never>>(
	main: Main,
	extras?: Extras
): Installable<Main> & Extras;

Example

ts
import { withInstall } from "@fast-china/utils";

const result = withInstall({ name: "FastMain" }, { Extra: { name: "FastExtra" } });

Input

InputTypeRequired / defaultDescription
mainMainRequiredComponent with a nonempty name.
extrasExtrasOptionalRelated components registered together and attached to the main component as enumerable properties.

Returns

ValueTypeDescription
resultInstallable<Main> & ExtrasOriginal main reference with typed install and extras properties.

withNoopInstall Install

Adds a no-op install function to a related component requiring no separate registration.

Signature

ts
export function withNoopInstall<Value extends VueInstallValue>(component: Value): TSXWithInstall<Value>;

Example

ts
import { withNoopInstall } from "@fast-china/utils";

const result = withNoopInstall({ name: "FastChild" });

Input

InputTypeRequired / defaultDescription
componentValueRequiredComponent with no own or inherited install property.

Returns

ValueTypeDescription
resultTSXWithInstall<Value>Original component reference with a side-effect-free install method.

withInstallDirective Directive

Adds plugin installation support to a Vue 3 directive.

Signature

ts
export function withInstallDirective<Value extends VueInstallValue>(directive: Value, name: string): Installable<Value>;

Example

ts
import { withInstallDirective } from "@fast-china/utils";

const result = withInstallDirective({ mounted: () => undefined }, "focus");

Input

InputTypeRequired / defaultDescription
directiveValueRequiredVue directive object with no own or inherited install property.
namestringRequiredNonempty global directive name without whitespace or a v- prefix.

Returns

ValueTypeDescription
resultInstallable<Value>Original directive reference with a Vue Plugin install method.

definePropType Props

Adds a generic type to a Vue runtime prop constructor.

Signature

ts
export function definePropType<Value>(runtimeType: unknown): PropType<Value>;

Example

ts
import { definePropType } from "@fast-china/utils";

const result = definePropType<string>(String);

Input

InputTypeRequired / defaultDescription
runtimeTypeunknownRequiredRuntime constructor or constructor array supported by Vue.

Returns

ValueTypeDescription
resultPropType<Value>Same reference, narrowed only at type level to PropType<Value>.

useProps Props

Builds reactive props to forward to a child component.

Signature

ts
export function useProps<Props extends object, RawProps extends object, IgnoredProp extends keyof RawProps = never>(
	props: Props,
	rawProps: RawProps,
	ignoredProps: readonly IgnoredProp[] = []
): ComputedRef<Omit<Pick<Props, Extract<keyof Props, keyof RawProps>>, Extract<IgnoredProp, keyof Props>>>;

Example

ts
import { useProps } from "@fast-china/utils";

const props = { internal: true, label: "Fast" };
const rawProps = { label: String };
const result = useProps(props, rawProps);

Input

InputTypeRequired / defaultDescription
propsPropsRequiredReadonly reactive props received by Vue setup.
rawPropsRawPropsRequiredChild component's runtime props configuration.
ignoredPropsreadonly IgnoredProp[]Optional; defaults to []Prop names not to forward.

Returns

ValueTypeDescription
resultComputedRef<Omit<Pick<Props, Extract<keyof Props, keyof RawProps>>, Extract<IgnoredProp, keyof Props>>>ComputedRef containing only keys declared by rawProps, updating with the props.

useRender Render

Installs a TSX render function on the current Vue 3 component instance.

Signature

ts
export function useRender(render: () => VNode): void;

Example

ts
import { useRender } from "@fast-china/utils";

import { h } from "vue";

useRender(() => h("div", "Fast"));

Input

InputTypeRequired / defaultDescription
render() => VNodeRequiredCurrent component's render function.

Returns

ValueTypeDescription
resultvoidNo return value.

makeSlots Slots

Creates scoped-slot types for the Options API slots option.

Signature

ts
export function makeSlots<Slots extends RawSlots>(): TypedSlotsDeclaration<Slots>;

Example

ts
import { makeSlots } from "@fast-china/utils";

const result = makeSlots<{ default: { title: string } }>();

Input

This method has no input parameters.

Returns

ValueTypeDescription
resultTypedSlotsDeclaration<Slots>Runtime Object constructor carrying a TypeScript-only slot type marker.

withDefineType Types

Preserves an input value while explicitly specifying its TypeScript type.

Signature

ts
export function withDefineType<Value>(data?: Value): Value;

Example

ts
import { withDefineType } from "@fast-china/utils";

const result = withDefineType<{ name: string }>({ name: "Fast" });

Input

InputTypeRequired / defaultDescription
dataValueOptionalOptional original value.

Returns

ValueTypeDescription
resultValueInput value itself; typed undefined when omitted.

useEventListener Listen

Registers a native event listener, removing it automatically when the reactive target changes or the Vue scope is disposed.

Signature

ts
export function useEventListener<EventType extends Event = Event>(
	target: EventTargetSource,
	event: string,
	listener: (event: EventType) => void,
	options?: boolean | AddEventListenerOptions
): () => void;

Example

ts
import { useEventListener } from "@fast-china/utils";

const stop = useEventListener(document, "visibilitychange", () => {
	console.log(document.visibilityState);
});

Input

InputTypeRequired / defaultDescription
targetEventTargetSourceRequiredNative EventTarget, Ref, or getter; may be nullish.
eventstringRequiredNative event name.
listener(event: EventType) => voidRequiredEvent callback.
optionsboolean | AddEventListenerOptionsOptionalNative addEventListener and removeEventListener options.

Returns

ValueTypeDescription
stop() => voidRemoves the listener early; also invoked automatically when the Vue scope is disposed.

useWindowSize Viewport

Reactively reads browser innerWidth and innerHeight.

Signature

ts
export function useWindowSize(): UseWindowSizeReturn;

Example

ts
import { useWindowSize } from "@fast-china/utils";

const { width, height } = useWindowSize();

Input

No input parameters. In browsers, call inside a Vue reactive scope to ensure listener cleanup.

Returns

ValueTypeDescription
widthReadonly<ShallowRef<number>>Current window.innerWidth; 0 outside browsers.
heightReadonly<ShallowRef<number>>Current window.innerHeight; 0 outside browsers.

Does not provide initial-size, Visual Viewport, Outer Size, or similar advanced options.

useResizeObserver Resize

Observes a single element or reactive element using native ResizeObserver.

Signature

ts
export function useResizeObserver(target: ResizeObserverTarget, callback: ResizeObserverCallback, options?: ResizeObserverOptions): () => void;

Example

ts
import { useResizeObserver } from "@fast-china/utils";

const stop = useResizeObserver(elementRef, (entries) => {
	console.log(entries[0]?.contentRect);
});

Input

InputTypeRequired / defaultDescription
targetResizeObserverTargetRequiredNative element, Ref, or getter; may be nullish.
callbackResizeObserverCallbackRequiredNative ResizeObserver callback.
optionsResizeObserverOptionsOptionalNative element-observation options.

Returns

ValueTypeDescription
stop() => voidDisconnects observation early; a no-op where ResizeObserver is unsupported.

useElementSize Size

Reactively reads an element's content-rectangle size through useResizeObserver.

Signature

ts
export function useElementSize(target: ResizeObserverTarget, initialSize?: ElementSize, options?: ResizeObserverOptions): UseElementSizeReturn;

Example

ts
import { useElementSize } from "@fast-china/utils";

const { width, height, stop } = useElementSize(elementRef, { height: 0, width: 0 });

Input

InputTypeRequired / defaultDescription
targetResizeObserverTargetRequiredNative element, Ref, or getter; may be nullish.
initialSizeElementSizeOptional; defaults to { width: 0, height: 0 }Width and height before the first observation.
optionsResizeObserverOptionsOptionalNative element-observation options.

Returns

ValueTypeDescription
widthReadonly<ShallowRef<number>>Element content-rectangle width.
heightReadonly<ShallowRef<number>>Element content-rectangle height.
stop() => voidStops the underlying ResizeObserver early.

useNow Clock

Provides reactive current time at a fixed interval.

Signature

ts
export function useNow(intervalMilliseconds?: number): Readonly<ShallowRef<Date>>;

Example

ts
import { useNow } from "@fast-china/utils";

const now = useNow();

Input

InputTypeRequired / defaultDescription
intervalMillisecondsnumberOptional; defaults to 1000Nonnegative integer interval in milliseconds within native timer limits.

Returns

ValueTypeDescription
nowReadonly<ShallowRef<Date>>Current time; SSR returns only a static Date captured at invocation.

In browsers and uni-app, call inside a Vue reactive scope; the timer stops with the scope.

useBreakpoints Breakpoints

Creates reactive minimum-width breakpoints using native matchMedia().

Signature

ts
export function useBreakpoints<Key extends string>(breakpoints: Breakpoints<Key>): UseBreakpointsReturn<Key>;

Example

ts
import { useBreakpoints } from "@fast-china/utils";

const breakpoints = useBreakpoints({ desktop: 1280, mobile: 0, tablet: 768 });
const active = breakpoints.active();

Input

InputTypeRequired / defaultDescription
breakpointsBreakpoints<Key>RequiredBreakpoint names and nonnegative minimum pixel widths; active is reserved.

Returns

ValueTypeDescription
Properties named after the breakpointsReadonly<ShallowRef<boolean>>Whether the current viewport meets the corresponding min-width.
active()ComputedRef<Key | "">Largest matching breakpoint; empty string when none matches.

All breakpoints are false outside browsers. In browsers, call inside a Vue reactive scope. Only min-width is supported.

Installable.install Install

Installs a result of withInstall, withNoopInstall, or withInstallDirective into a Vue app.

Signature

ts
install(app: App): void;

Example

ts
import { createApp } from "vue";
import { FastComponent } from "./component";

const app = createApp({});
app.use(FastComponent);

Input

InputTypeRequired / defaultDescription
appAppRequiredVue 3 app providing component() and directive().

Returns

ValueTypeDescription
resultvoidNo return value; invalid component or directive names throw.