コンテンツにスキップ

useFocus

カテゴリ
エクスポートサイズ
605 B
最終変更
先週

DOM要素のフォーカス状態を追跡または設定するためのリアクティブなユーティリティ。ターゲット要素がフォーカスされた要素であるかどうかを反映するように状態が変化します。外部からのリアクティブな値の設定は、truefalse の値に対してそれぞれ focusblur イベントをトリガーします。

デモ

フォーカスできる段落


基本的な使い方

ts
import { useFocus } from '@vueuse/core'

const target = ref()
const { focused } = useFocus(target)

watch(focused, (focused) => {
  if (focused)
    console.log('input element has been focused')
  else console.log('input element has lost focus')
})

初期フォーカスの設定

最初のレンダリング時に要素をフォーカスするには、initialValue オプションを true として指定します。これにより、ターゲット要素で focus イベントがトリガーされます。

ts
import { useFocus } from '@vueuse/core'

const target = ref()
const { focused } = useFocus(target, { initialValue: true })

フォーカス状態の変更

focused リアクティブ ref の変更は、truefalse の値に対してそれぞれ focusblur イベントを自動的にトリガーします。この動作を利用して、別の操作の結果としてターゲット要素をフォーカスすることができます (例:下記に示すようなボタンクリック時)。

vue
<script>
import { useFocus } from '@vueuse/core'
import { ref } from 'vue'

export default {
  setup() {
    const input = ref()
    const { focused } = useFocus(input)

    return {
      input,
      focused,
    }
  }
}
</script>

<template>
  <div>
    <button type="button" @click="focused = true">
      Click me to focus input below
    </button>
    <input ref="input" type="text">
  </div>
</template>

型定義

typescript
export interface UseFocusOptions extends ConfigurableWindow {
  /**
   * Initial value. If set true, then focus will be set on the target
   *
   * @default false
   */
  initialValue?: boolean
  /**
   * Replicate the :focus-visible behavior of CSS
   *
   * @default false
   */
  focusVisible?: boolean
  /**
   * Prevent scrolling to the element when it is focused.
   *
   * @default false
   */
  preventScroll?: boolean
}
export interface UseFocusReturn {
  /**
   * If read as true, then the element has focus. If read as false, then the element does not have focus
   * If set to true, then the element will be focused. If set to false, the element will be blurred.
   */
  focused: Ref<boolean>
}
/**
 * Track or set the focus state of a DOM element.
 *
 * @see https://vueuse.dokyumento.jp/useFocus
 * @param target The target element for the focus and blur events.
 * @param options
 */
export declare function useFocus(
  target: MaybeElementRef,
  options?: UseFocusOptions,
): UseFocusReturn

ソース

ソースデモドキュメント

コントリビューター

Anthony Fu
William T. Kirby
Anthony Fu
陪我去看海吧
Max
Waleed Khaled
Jelf
ByMykel
Levi Bucsis
webfansplz
Jakub Freisler

変更履歴

v12.0.0-beta.1 2024/11/21
0a9ed - feat!: Vue 2 のサポートを廃止、バンドルを最適化し、クリーンアップ (#4349)
v10.10.1 2024/06/11
4d868 - feat: preventScrollオプションのサポート (#3994)
v10.3.0 2023年7月30日
80329 - feat: :focus-visible のサポート (#3254)
v9.13.0 2023年2月18日
7cd88 - fix: targetElementfocusblur をリッスンする (#2631)

MITライセンスの下でリリースされています。