Skip to content

useFocusWithin

Category
Export Size
1.13 kB
Last Changed
2 months ago

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

Demo

Focus in form: false

基本用法

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

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>

Type Declarations

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/useFocusWithin
 * @param target The target element to track
 * @param options Focus within options
 */
export declare function useFocusWithin(
  target: MaybeElementRef,
  options?: ConfigurableWindow,
): UseFocusWithinReturn

Source

SourceDemoDocs

Contributors

Anthony Fu
丶远方
Anthony Fu
Ben Lau
autofix-ci[bot]
IlyaL
Fernando Fernández
sun0day
Mikhailov Nikita
Boris Moiseev
Jelf
William T. Kirby

Changelog

dd316 - feat: use passive event handlers everywhere is possible (#4477)
3ca0d - fix: correctly track the state when switching the focus of elements in the same container (#4394)
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)
c5407 - fix: make useFocusWhithin match the behavior of the :focus-within (#4134)
e75a5 - feat: update deps

Released under the MIT License.