useFocusWithin
要素またはその子孫のいずれかにフォーカスがあるかどうかを追跡するリアクティブユーティリティ。:focus-within
CSS疑似クラスの動作に一致するように設計されています。一般的な使用例としては、フォーム要素で、その入力のいずれかに現在フォーカスがあるかどうかを確認する場合などがあります。
デモ
フォームにフォーカス: 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.dokyumento.jp/useFocusWithin
* @param target The target element to track
* @param options Focus within options
*/
export declare function useFocusWithin(
target: MaybeElementRef,
options?: ConfigurableWindow,
): UseFocusWithinReturn