Skip to content

useFocusWithin

类别
导出大小
1.37 kB
最近修改
2 days ago

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

🌐 Reactive utility to track if an element or one of its decendants has focus. It is meant to match the behavior of the :focus-within CSS pseudo-class. A common use case would be on a form element to see if any of its inputs currently have focus.

示例

Focus in form: false

基本用法

🌐 Basic Usage

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>