跳到内容

useFocusWithin

类别
导出大小
1.13 kB
最后更改
3 周前

用于跟踪元素或其后代之一是否具有焦点的响应式实用程序。它旨在匹配 :focus-within CSS 伪类的行为。一个常见的用例是在表单元素上查看其任何输入当前是否具有焦点。

演示

表单中聚焦: false

基本用法

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

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

watch(focused, (focused) => {
  if (focused)
    console.log('Target contains the focused element')
  else console.log('Target does NOT contain the focused element')
})
</script>

<template>
  <form ref="target">
    <input type="text" placeholder="First Name">
    <input type="text" placeholder="Last Name">
    <input type="text" placeholder="Email">
    <input type="text" placeholder="Password">
  </form>
</template>

类型声明

typescript
export interface UseFocusWithinReturn {
  /**
   * True if the element or any of its descendants are focused
   */
  focused: ComputedRef<boolean>
}
/**
 * Track if focus is contained within the target element
 *
 * @see https://vueuse.org.cn/useFocusWithin
 * @param target The target element to track
 * @param options Focus within options
 */
export declare function useFocusWithin(
  target: MaybeElementRef,
  options?: ConfigurableWindow,
): UseFocusWithinReturn

源代码

SourceDemoDocs

贡献者

Anthony Fu
Anthony Fu
Ben Lau
IlyaL
Fernando Fernández
sun0day
Mikhailov Nikita
Boris Moiseev
Jelf
William T. Kirby

更新日志

v12.4.0 on 1/10/2025
dd316 - feat: use passive event handlers everywhere is possible (#4477)
v12.3.0 on 1/2/2025
3ca0d - fix: correctly track the state when switching the focus of elements in the same container (#4394)
v12.0.0-beta.1 on 11/21/2024
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)
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

在 MIT 许可证下发布。