基于vue3.0和element-plus的组件库
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

1.5 KiB

useWatchOnce (watchEffectOnce)

One-time watch utility that auto-unmounts after condition is met.

Purpose

Executes a callback once when a reactive condition becomes truthy, then automatically stops watching.

Signature

export function watchEffectOnce(cond: Ref<any, any>, cb: WatchEffect): WatchStopHandle

Parameters

Parameter Type Description
cond Ref<any> Reactive condition to watch
cb WatchEffect Callback when condition is true

Return Value

Type Description
WatchStopHandle Function to manually stop the watcher

Usage Pattern

// Example: plugs/composables/useWatchOnce.ts
import { ref } from "vue";
import { watchEffectOnce } from "plugs/composables";

const isReady = ref(false);

watchEffectOnce(isReady, (onCleanup) => {
  console.log("Ready!");
  // Optional: register cleanup
  onCleanup(() => {
    console.log("Cleanup when stopped");
  });
});

isReady.value = true; // Triggers callback and stops watching

Key Implementation Details

  1. Auto-stop: Uses nextTick + stop() after condition is met
  2. One-shot: Callback fires only on first truthy value
  3. Cleanup support: Passes onCleanup callback for disposal logic

Dependencies

  • vue - nextTick, ref, watchEffect

Anti-patterns

  • Do not use for ongoing watches; this is specifically for one-time triggers
  • Do not rely on the watcher persisting; it stops after first trigger