Lzh on GitHub

响应式的 document.activeElement (当前获得焦点的元素)。

Demo

使用

import { useActiveElement } from '@vueuse/core'

const activeElement = useActiveElement()

watch(activeElement, (el) => {
  console.log('focus changed to', el)
})
  • useActiveElement 监听的是 document.activeElement,如果你在 SSR 环境中使用,需要确保是在 onMounted 之后访问。
  • 如果你使用的是

组件方式使用

此函数也通过 @vueuse/components 包提供一个无渲染组件版本。了解更多用法

<template>
  <UseActiveElement v-slot="{ element }">
    Active element is {{ element.dataset.id }}
  </UseActiveElement>
</template>

类型声明

export interface UseActiveElementOptions
  extends ConfigurableWindow,
    ConfigurableDocumentOrShadowRoot {
  /**
   * Search active element deeply inside shadow dom
   *
   * @default true
   */
  deep?: boolean
  /**
   * Track active element when it's removed from the DOM
   * Using a MutationObserver under the hood
   * @default false
   */
  triggerOnRemoval?: boolean
}
/**
 * Reactive `document.activeElement`
 *
 * @see https://vueuse.org/useActiveElement
 * @param options
 */
export declare function useActiveElement<T extends HTMLElement>(
  options?: UseActiveElementOptions,
): ShallowRef<T | null | undefined, T | null | undefined>