跳到内容

useFocus

类别
导出大小
718 B
最后更改
3 周前

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

演示

可以聚焦的段落


基本用法

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

const target = shallowRef()
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 = shallowRef()
const { focused } = useFocus(target, { initialValue: true })

更改焦点状态

focused 响应式 ref 的更改将自动为 truefalse 值分别触发 focusblur 事件。您可以利用此行为在另一个操作的结果中聚焦目标元素(例如,当按钮单击时,如下所示)。

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

export default {
  setup() {
    const input = shallowRef()
    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: WritableComputedRef<boolean>
}
/**
 * Track or set the focus state of a DOM element.
 *
 * @see https://vueuse.org.cn/useFocus
 * @param target The target element for the focus and blur events.
 * @param options
 */
export declare function useFocus(
  target: MaybeElementRef,
  options?: UseFocusOptions,
): UseFocusReturn

源代码

SourceDemoDocs

贡献者

Anthony Fu
IlyaL
Anthony Fu
William T. Kirby
Robin
Fernando Fernández
陪我去看海吧
Max
Waleed Khaled
Jelf
ByMykel
Levi Bucsis
webfansplz
Jakub Freisler

更新日志

v12.4.0 于 2025/1/10
dd316 - feat: use passive event handlers everywhere is possible (#4477)
v12.0.0-beta.1 于 2024/11/21
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)
v10.10.1 于 2024/6/11
4d868 - feat: support preventScroll option (#3994)
v10.3.0 于 2023/7/30
80329 - feat: support :focus-visible (#3254)
v9.13.0 于 2023/2/18
7cd88 - fix: listen focus and blur to the targetElement (#2631)

在 MIT 许可证下发布。