useFocus
DOM要素のフォーカス状態を追跡または設定するためのリアクティブなユーティリティ。ターゲット要素がフォーカスされた要素であるかどうかを反映するように状態が変化します。外部からのリアクティブな値の設定は、true
と false
の値に対してそれぞれ focus
と blur
イベントをトリガーします。
デモ
フォーカスできる段落
基本的な使い方
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 の変更は、true
と false
の値に対してそれぞれ focus
と blur
イベントを自動的にトリガーします。この動作を利用して、別の操作の結果としてターゲット要素をフォーカスすることができます (例:下記に示すようなボタンクリック時)。
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