Vue 3 helpers API
useEmits Events
Builds reactive Vue event handlers.
Signature
export function useEmits<Emits extends EmitsOptions>(
emits: Emits,
emit: (...arguments_: never[]) => unknown,
ignoredEvents: readonly (keyof Emits)[] = []
): ComputedRef<Partial<EmitHandlers<Emits>>>;Example
import { useEmits } from "@fast-china/utils";
const result = useEmits({ change: null }, () => undefined);Input
| Input | Type | Required / default | Description |
|---|---|---|---|
emits | Emits | Required | Vue emits configuration object. |
emit | (...arguments_: never[]) => unknown | Required | Emit function provided by the setup context. |
ignoredEvents | readonly (keyof Emits)[] | Optional; defaults to [] | Event names not to forward to the child component. |
Returns
| Value | Type | Description |
|---|---|---|
result | ComputedRef<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
export function useExpose<Exposed extends object>(expose: (exposed?: Exposed) => void, exposed: Exposed): Exposed;Example
import { useExpose } from "@fast-china/utils";
const exposed = { focus: () => undefined };
const result = useExpose((value) => console.log(value), exposed);Input
| Input | Type | Required / default | Description |
|---|---|---|---|
expose | (exposed?: Exposed) => void | Required | Expose function provided by the setup context. |
exposed | Exposed | Required | State and methods to expose. |
Returns
| Value | Type | Description |
|---|---|---|
result | Exposed | Original exposed object. |
callOptionalFunction Invoke
Executes a synchronous or asynchronous function, propagating exceptions unchanged.
Signature
export async function callOptionalFunction<Arguments extends readonly unknown[], Result>(
function_: AwaitableFunction<Arguments, Result> | null | undefined,
...arguments_: Arguments
): Promise<Awaited<Result> | undefined>;Example
import { callOptionalFunction } from "@fast-china/utils";
const result = await callOptionalFunction((value: string) => value.length, "Fast");Input
| Input | Type | Required / default | Description |
|---|---|---|---|
function_ | AwaitableFunction<Arguments, Result> | null | undefined | Required | Optional function to execute. |
arguments_ | Arguments | Required | Arguments forwarded unchanged. |
Returns
| Value | Type | Description |
|---|---|---|
result | Promise<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
export function withInstall<Main extends VueInstallValue, Extras extends Record<string, VueInstallValue> = Record<never, never>>(
main: Main,
extras?: Extras
): Installable<Main> & Extras;Example
import { withInstall } from "@fast-china/utils";
const result = withInstall({ name: "FastMain" }, { Extra: { name: "FastExtra" } });Input
| Input | Type | Required / default | Description |
|---|---|---|---|
main | Main | Required | Component with a nonempty name. |
extras | Extras | Optional | Related components registered together and attached to the main component as enumerable properties. |
Returns
| Value | Type | Description |
|---|---|---|
result | Installable<Main> & Extras | Original 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
export function withNoopInstall<Value extends VueInstallValue>(component: Value): TSXWithInstall<Value>;Example
import { withNoopInstall } from "@fast-china/utils";
const result = withNoopInstall({ name: "FastChild" });Input
| Input | Type | Required / default | Description |
|---|---|---|---|
component | Value | Required | Component with no own or inherited install property. |
Returns
| Value | Type | Description |
|---|---|---|
result | TSXWithInstall<Value> | Original component reference with a side-effect-free install method. |
withInstallDirective Directive
Adds plugin installation support to a Vue 3 directive.
Signature
export function withInstallDirective<Value extends VueInstallValue>(directive: Value, name: string): Installable<Value>;Example
import { withInstallDirective } from "@fast-china/utils";
const result = withInstallDirective({ mounted: () => undefined }, "focus");Input
| Input | Type | Required / default | Description |
|---|---|---|---|
directive | Value | Required | Vue directive object with no own or inherited install property. |
name | string | Required | Nonempty global directive name without whitespace or a v- prefix. |
Returns
| Value | Type | Description |
|---|---|---|
result | Installable<Value> | Original directive reference with a Vue Plugin install method. |
definePropType Props
Adds a generic type to a Vue runtime prop constructor.
Signature
export function definePropType<Value>(runtimeType: unknown): PropType<Value>;Example
import { definePropType } from "@fast-china/utils";
const result = definePropType<string>(String);Input
| Input | Type | Required / default | Description |
|---|---|---|---|
runtimeType | unknown | Required | Runtime constructor or constructor array supported by Vue. |
Returns
| Value | Type | Description |
|---|---|---|
result | PropType<Value> | Same reference, narrowed only at type level to PropType<Value>. |
useProps Props
Builds reactive props to forward to a child component.
Signature
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
import { useProps } from "@fast-china/utils";
const props = { internal: true, label: "Fast" };
const rawProps = { label: String };
const result = useProps(props, rawProps);Input
| Input | Type | Required / default | Description |
|---|---|---|---|
props | Props | Required | Readonly reactive props received by Vue setup. |
rawProps | RawProps | Required | Child component's runtime props configuration. |
ignoredProps | readonly IgnoredProp[] | Optional; defaults to [] | Prop names not to forward. |
Returns
| Value | Type | Description |
|---|---|---|
result | ComputedRef<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
export function useRender(render: () => VNode): void;Example
import { useRender } from "@fast-china/utils";
import { h } from "vue";
useRender(() => h("div", "Fast"));Input
| Input | Type | Required / default | Description |
|---|---|---|---|
render | () => VNode | Required | Current component's render function. |
Returns
| Value | Type | Description |
|---|---|---|
result | void | No return value. |
makeSlots Slots
Creates scoped-slot types for the Options API slots option.
Signature
export function makeSlots<Slots extends RawSlots>(): TypedSlotsDeclaration<Slots>;Example
import { makeSlots } from "@fast-china/utils";
const result = makeSlots<{ default: { title: string } }>();Input
This method has no input parameters.
Returns
| Value | Type | Description |
|---|---|---|
result | TypedSlotsDeclaration<Slots> | Runtime Object constructor carrying a TypeScript-only slot type marker. |
withDefineType Types
Preserves an input value while explicitly specifying its TypeScript type.
Signature
export function withDefineType<Value>(data?: Value): Value;Example
import { withDefineType } from "@fast-china/utils";
const result = withDefineType<{ name: string }>({ name: "Fast" });Input
| Input | Type | Required / default | Description |
|---|---|---|---|
data | Value | Optional | Optional original value. |
Returns
| Value | Type | Description |
|---|---|---|
result | Value | Input 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
export function useEventListener<EventType extends Event = Event>(
target: EventTargetSource,
event: string,
listener: (event: EventType) => void,
options?: boolean | AddEventListenerOptions
): () => void;Example
import { useEventListener } from "@fast-china/utils";
const stop = useEventListener(document, "visibilitychange", () => {
console.log(document.visibilityState);
});Input
| Input | Type | Required / default | Description |
|---|---|---|---|
target | EventTargetSource | Required | Native EventTarget, Ref, or getter; may be nullish. |
event | string | Required | Native event name. |
listener | (event: EventType) => void | Required | Event callback. |
options | boolean | AddEventListenerOptions | Optional | Native addEventListener and removeEventListener options. |
Returns
| Value | Type | Description |
|---|---|---|
stop | () => void | Removes the listener early; also invoked automatically when the Vue scope is disposed. |
useWindowSize Viewport
Reactively reads browser innerWidth and innerHeight.
Signature
export function useWindowSize(): UseWindowSizeReturn;Example
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
| Value | Type | Description |
|---|---|---|
width | Readonly<ShallowRef<number>> | Current window.innerWidth; 0 outside browsers. |
height | Readonly<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
export function useResizeObserver(target: ResizeObserverTarget, callback: ResizeObserverCallback, options?: ResizeObserverOptions): () => void;Example
import { useResizeObserver } from "@fast-china/utils";
const stop = useResizeObserver(elementRef, (entries) => {
console.log(entries[0]?.contentRect);
});Input
| Input | Type | Required / default | Description |
|---|---|---|---|
target | ResizeObserverTarget | Required | Native element, Ref, or getter; may be nullish. |
callback | ResizeObserverCallback | Required | Native ResizeObserver callback. |
options | ResizeObserverOptions | Optional | Native element-observation options. |
Returns
| Value | Type | Description |
|---|---|---|
stop | () => void | Disconnects observation early; a no-op where ResizeObserver is unsupported. |
useElementSize Size
Reactively reads an element's content-rectangle size through useResizeObserver.
Signature
export function useElementSize(target: ResizeObserverTarget, initialSize?: ElementSize, options?: ResizeObserverOptions): UseElementSizeReturn;Example
import { useElementSize } from "@fast-china/utils";
const { width, height, stop } = useElementSize(elementRef, { height: 0, width: 0 });Input
| Input | Type | Required / default | Description |
|---|---|---|---|
target | ResizeObserverTarget | Required | Native element, Ref, or getter; may be nullish. |
initialSize | ElementSize | Optional; defaults to { width: 0, height: 0 } | Width and height before the first observation. |
options | ResizeObserverOptions | Optional | Native element-observation options. |
Returns
| Value | Type | Description |
|---|---|---|
width | Readonly<ShallowRef<number>> | Element content-rectangle width. |
height | Readonly<ShallowRef<number>> | Element content-rectangle height. |
stop | () => void | Stops the underlying ResizeObserver early. |
useTransition Numeric transition
Smooth changes to a numeric ref or getter. Available since 2.1.10; supports a single finite number.
Signature
export interface UseTransitionOptions {
duration?: number;
transition?: (progress: number) => number;
}
export function useTransition(source: MaybeRefOrGetter<number>, options?: UseTransitionOptions): Readonly<ShallowRef<number>>;Example
Call inside component setup or an effectScope:
import { useTransition } from "@fast-china/utils";
import { shallowRef } from "vue";
const target = shallowRef(0);
const displayed = useTransition(target, { duration: 500, transition: (progress) => progress ** 2 });
target.value = 100;Input
| Input | Type | Required/default | Description |
|---|---|---|---|
source | MaybeRefOrGetter<number> | Required | Finite number, ref, or getter |
options.duration | number | Optional, 300 | Nonnegative finite milliseconds; 0 synchronizes immediately |
options.transition | (progress: number) => number | Optional, linear | Maps progress from 0 to 1 to a finite interpolation weight; overshoot is allowed |
Returns
| Value | Type | Description |
|---|---|---|
displayed | Readonly<ShallowRef<number>> | Starts at the source value and animates subsequent changes |
Timing starts at the first animation frame. A new target starts from the current displayed value; completion sets the exact target. Options are read once. Browsers require an active Vue scope, otherwise an Error is thrown; stopping the scope cancels animation frames. SSR and hosts without requestAnimationFrame/cancelAnimationFrame follow the reactive input immediately without scheduling animation.
Invalid initial values or durations throw RangeError synchronously; later invalid input is reported by the Vue watcher. Easing exceptions propagate; nonfinite easing or interpolation results throw RangeError in the animation frame and stop scheduling that animation. Pause, delay, and array interpolation are not provided.
useNow Clock
Provides reactive current time at a fixed interval.
Signature
export function useNow(intervalMilliseconds?: number): Readonly<ShallowRef<Date>>;Example
import { useNow } from "@fast-china/utils";
const now = useNow();Input
| Input | Type | Required / default | Description |
|---|---|---|---|
intervalMilliseconds | number | Optional; defaults to 1000 | Nonnegative integer interval in milliseconds within native timer limits. |
Returns
| Value | Type | Description |
|---|---|---|
now | Readonly<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
export function useBreakpoints<Key extends string>(breakpoints: Breakpoints<Key>): UseBreakpointsReturn<Key>;Example
import { useBreakpoints } from "@fast-china/utils";
const breakpoints = useBreakpoints({ desktop: 1280, mobile: 0, tablet: 768 });
const active = breakpoints.active();Input
| Input | Type | Required / default | Description |
|---|---|---|---|
breakpoints | Breakpoints<Key> | Required | Breakpoint names and nonnegative minimum pixel widths; active is reserved. |
Returns
| Value | Type | Description |
|---|---|---|
| Properties named after the breakpoints | Readonly<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
install(app: App): void;Example
Install the dependencies in an empty directory.
npm init -y
npm install vue @fast-china/utilsCreate install.mjs.
import { createApp } from "vue";
import { withInstall } from "@fast-china/utils";
const FastComponent = withInstall({ name: "FastComponent" });
const app = createApp({}).use(FastComponent);
console.log(app.component("FastComponent") === FastComponent);Run node install.mjs. Expect true.
Input
| Input | Type | Required / default | Description |
|---|---|---|---|
app | App | Required | Vue 3 app providing component() and directive(). |
Returns
| Value | Type | Description |
|---|---|---|
result | void | No return value; invalid component or directive names throw. |
