useFocusWithin
追蹤元素或其後代是否具有焦點的響應式工具。它旨在匹配 :focus-within
CSS 偽類別的行為。常見的用例是在表單元素上查看其任何輸入目前是否具有焦點。
Demo
表單中的焦點:false
基本用法
vue
<script>
import { useFocusWithin } from '@vueuse/core'
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>
類型宣告
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.dev.org.tw/useFocusWithin
* @param target The target element to track
* @param options Focus within options
*/
export declare function useFocusWithin(
target: MaybeElementRef,
options?: ConfigurableWindow,
): UseFocusWithinReturn
原始碼
貢獻者
更新日誌
v12.4.0
於 2025/1/10v12.3.0
於 2025/1/2v12.0.0-beta.1
於 2024/11/21v11.1.0
於 2024/9/16v10.0.0-beta.3
於 2023/4/12e75a5
- feat: 更新依賴