Skip to content

useFocusWithin

Category
Export Size
769 B
Last Changed
15 minutes ago

用于跟踪一个元素或其子元素是否具有焦点的响应式工具。它的行为类似于 :focus-within CSS 伪类。一个常见的用例是在表单元素上,以查看其任何输入框当前是否具有焦点。

Demo

Focus in form: false

基本用法

vue
<script>
import { ref, watch } from 'vue'
import { useFocusWithin } from '@vueuse/core'

const target = ref()
const { focused } = useFocusWithin(target)

watch(focused, (focused) => {
  if (focused)
    console.log('目标包含有焦点的元素')
  else console.log('目标不包含有焦点的元素')
})
</script>

<template>
  <form ref="target">
    <input type="text" placeholder="">
    <input type="text" placeholder="">
    <input type="text" placeholder="电子邮件">
    <input type="text" placeholder="密码">
  </form>
</template>

类型声明

typescript
export interface UseFocusWithinReturn {
  /**
   * 如果该元素或其任何子元素获得焦点,则为 true
   */
  focused: ComputedRef<boolean>
}
/**
 * 跟踪焦点是否包含在目标元素内
 *
 * @see https://vueuse.org/useFocusWithin
 * @param target The target element to track
 * @param options Focus within options
 */
export declare function useFocusWithin(
  target: MaybeElementRef,
  options?: ConfigurableWindow,
): UseFocusWithinReturn

Source

SourceDemoDocs

贡献者

Anthony Fu
丶远方
Anthony Fu
Ben Lau
sun0day
Mikhailov Nikita
Boris Moiseev
Jelf
William T. Kirby

变更日志

v11.1.0 on 9/16/2024
c5407 - fix: make useFocusWhithin match the behavior of the :focus-within (#4134)
v10.0.0-beta.3 on 4/12/2023
e75a5 - feat: update deps

Released under the MIT License.