useFocusWithin
用于跟踪一个元素或其子元素是否具有焦点的响应式工具。它的行为类似于 :focus-within
CSS 伪类。一个常见的用例是在表单元素上,以查看其任何输入框当前是否具有焦点。
示例
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
源码
贡献者
Anthony Fu
一纸忘忧
Ben Lau
Fernando Fernández
Anthony Fu
sun0day
Mikhailov Nikita
Boris Moiseev
Jelf
William T. Kirby
更新日志
v12.4.0
on 1/10/2025v12.3.0
on 1/2/20253ca0d
- fix: correctly track the state when switching the focus of elements in the same container (#4394)v12.0.0-beta.1
on 11/21/2024v11.1.0
on 9/16/2024v10.0.0-beta.3
on 4/12/2023e75a5
- feat: update deps