Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Apply VueUse composables in Vue 3/Nuxt projects to replace custom implementations with battle-tested utilities.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/useFocus.md
1---2category: Sensors3---45# useFocus67Reactive utility to track or set the focus state of a DOM element. State changes to reflect whether the target element is the focused element. Setting reactive value from the outside will trigger `focus` and `blur` events for `true` and `false` values respectively.89## Basic Usage1011```ts12import { useFocus } from '@vueuse/core'1314const target = shallowRef()15const { focused } = useFocus(target)1617watch(focused, (focused) => {18if (focused)19console.log('input element has been focused')20else console.log('input element has lost focus')21})22```2324## Setting initial focus2526To focus the element on its first render one can provide the `initialValue` option as `true`. This will trigger a `focus` event on the target element.2728```ts29import { useFocus } from '@vueuse/core'3031const target = shallowRef()32const { focused } = useFocus(target, { initialValue: true })33```3435## Change focus state3637Changes of the `focused` reactive ref will automatically trigger `focus` and `blur` events for `true` and `false` values respectively. You can utilize this behavior to focus the target element as a result of another action (e.g. when a button click as shown below).3839```vue40<script setup lang="ts">41import { useFocus } from '@vueuse/core'42import { shallowRef } from 'vue'4344const input = shallowRef()45const { focused } = useFocus(input)46</script>4748<template>49<div>50<button type="button" @click="focused = true">51Click me to focus input below52</button>53<input ref="input" type="text">54</div>55</template>56```5758## Type Declarations5960```ts61export interface UseFocusOptions extends ConfigurableWindow {62/**63* Initial value. If set true, then focus will be set on the target64*65* @default false66*/67initialValue?: boolean68/**69* Replicate the :focus-visible behavior of CSS70*71* @default false72*/73focusVisible?: boolean74/**75* Prevent scrolling to the element when it is focused.76*77* @default false78*/79preventScroll?: boolean80}81export interface UseFocusReturn {82/**83* If read as true, then the element has focus. If read as false, then the element does not have focus84* If set to true, then the element will be focused. If set to false, the element will be blurred.85*/86focused: WritableComputedRef<boolean>87}88/**89* Track or set the focus state of a DOM element.90*91* @see https://vueuse.org/useFocus92* @param target The target element for the focus and blur events.93* @param options94*/95export declare function useFocus(96target: MaybeElementRef,97options?: UseFocusOptions,98): UseFocusReturn99```100