跳到主要内容

useFocusWithin

分类
导出大小
1.37 kB
上次更改
8 个月前

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

演示

表单内部焦点: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
('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>

类型声明

ts
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

来源

源文件演示文档

贡献者

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

更新日志

v12.4.0
dd316 - feat: 尽可能在所有地方使用被动事件处理程序 (#4477)
v12.3.0
3ca0d - 修复:在同一容器中切换元素焦点时正确跟踪状态(#4394
0a9ed - feat!: 放弃对 Vue 2 的支持,优化打包并清理 (#4349)
v11.1.0
c5407 - 修复:使 useFocusWhithin 匹配 :focus-within 的行为(#4134

根据 MIT 许可证发布。