UseActiveElement: Listens for active elements on the current page and automatically unlistens when the component is destroyed
use
import { useActiveElement } from '@vueuse/core'
const activeElement = useActiveElement()
watch(activeElement, (el) => {
console.log('focus changed to', el)
})
Copy the code
API source code
function useActiveElement(options = {}) {
const { window = defaultWindow } = options;
const counter = ref(0);
if (window) {
useEventListener(window, "blur", () => counter.value += 1, true);
useEventListener(window, "focus", () => counter.value += 1, true);
}
return computed(() => {
counter.value;
return window == null ? void 0 : window.document.activeElement;
});
}
Copy the code
useEventListener
The source code uses another method, useEventListener, which automatically listens for the Cancel event when the component is destroyed
function useEventListener(... args) { let target; let event; let listener; let options; if (isString(args[0])) { [event, listener, options] = args; target = defaultWindow; } else { [target, event, listener, options] = args; } if (! target) return noop; let cleanup = noop; const stopWatch = watch(() => unref(target), (el) => { cleanup(); if (! el) return; el.addEventListener(event, listener, options); cleanup = () => { el.removeEventListener(event, listener, options); cleanup = noop; }; }, { immediate: true, flush: "post" }); const stop = () => { stopWatch(); cleanup(); }; tryOnScopeDispose(stop); return stop; }Copy the code
About blur not bubbling
UseEventListener triggers the event in the capture phase during the listening process of both focus and blur events. Because blur events do not bubble, the blur event of the element cannot be monitored on the window.
For information about event capture and bubbling, see Javascript Event capture and Event bubbling
Side effect refresh time
Vue’s responsive system caches side effects functions and refreshes them asynchronously to avoid unnecessary repeated calls due to multiple state changes in the same “tick.” In the concrete implementation of the core, the component’s update function is also a monitored side effect. When a user-defined side effect function is queued, it is executed by default before all component updates
UseEventListener The third argument to the watch function flush: ‘post’ ensures that event listeners are bound after the component’s update() call, ensuring that the DOM has been rendered.
-
Flush: ‘pre’ By default, all custom side effects are executed before component update
-
Flush: ‘POST’ All custom side effects functions are executed after a component update, usually to retrieve the DOM after the update
-
Flust: ‘sync’ is generally not used, if so, this will force the effect to always fire synchronously. However, this is inefficient and should rarely be needed