Skip to content

useFocusWithin

类别
导出体积
1.37 kB
上次更改
last year

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

示例

Focus in form: false

基本用法

vue
<script setup lang="ts">
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>

类型声明

ts
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
一纸忘忧
Anthony Fu
Ben Lau
一纸忘忧
Sam Blowes
Vida Xie
SerKo
IlyaL
Fernando Fernández
sun0day
Mikhailov Nikita
Boris Moiseev
Jelf
William T. Kirby

更新日志

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)