Skip to content

useFocus

用于跟踪或设置 DOM 元素的焦点状态的响应式工具。状态更改以反映目标元素是否是焦点元素。从外部设置无功值将分别针对 truefalse 值触发 focusblur 事件。

¥Reactive 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.

示例

Paragraph that can be focused


基本用法

¥Basic Usage

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')
})

设置初始焦点

¥Setting initial focus

要将元素集中在其第一个渲染上,可以提供 initialValue 选项作为 true。这将在目标元素上触发 focus 事件。

¥To 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.

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

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

改变焦点状态

¥Change focus state

focused 无功参考值的变化将自动分别针对 truefalse 值触发 focusblur 事件。你可以利用此行为作为另一个操作的结果来聚焦目标元素(例如,当单击按钮时,如下所示)。

¥Changes 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).

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

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.org/useFocus
 * @param target The target element for the focus and blur events.
 * @param options
 */
export declare function useFocus(
  target: MaybeElementRef,
  options?: UseFocusOptions,
): UseFocusReturn

源代码

源代码示例文档

变更日志

No recent changes

VueUse 中文网 - 粤ICP备13048890号