useFocusWithin

useFocusWithin

要素またはその子孫のいずれかがフォーカスを持っているかどうかを追跡するリアクティブユーティリティです。これは、:focus-within CSS疑似クラスの動作に一致することを目的としています。一般的な使用例としては、フォーム要素でその入力のいずれかが現在フォーカスを持っているかどうかを確認することです。

基本的な使用法

<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="First Name">
    <input type="text" placeholder="Last Name">
    <input type="text" placeholder="Email">
    <input type="text" placeholder="Password">
  </form>
</template>