Skip to content

useFocus

类别
导出体积
754 B
上次更改
last year

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

示例

可获得焦点的段落


基本用法

ts
import { 
useFocus
} from '@vueuse/core'
const
target
=
shallowRef
()
const {
focused
} =
useFocus
(
target
)
watch
(
focused
, (
focused
) => {
if (
focused
)
console
.
log
('输入元素已获取焦点')
else
console
.
log
('输入元素已失去焦点')
})

设置初始焦点

可以通过将 initialValue 选项设置为 true 来在首次渲染时让元素获得焦点。这将触发目标元素上的 focus 事件。

ts
import { 
useFocus
} from '@vueuse/core'
const
target
=
shallowRef
()
const {
focused
} =
useFocus
(
target
, {
initialValue
: true })

更改焦点状态

focused 响应式引用的更改将自动触发对应于 truefalse 值的 focusblur 事件。你可以利用这种行为来作为其他操作的结果使目标元素获得焦点 (例如,当按钮被点击时,如下所示)。

vue
<script setup lang="ts">
import { 
useFocus
} from '@vueuse/core'
import {
shallowRef
} from 'vue'
const
input
=
shallowRef
()
const {
focused
} =
useFocus
(
input
)
</script> <template> <
div
>
<
button
type
="button" @
click
="
focused
= true">
单击我以使下面的输入框获得焦点 </
button
>
<
input
ref
="
input
"
type
="text">
</
div
>
</template>

类型声明

ts
export interface UseFocusOptions extends ConfigurableWindow {
  /**
   * 初始值。如果设置为 true,则焦点将设置在目标上
   *
   * @default false
   */
  
initialValue
?: boolean
/** * 复制 CSS 的 :focus-visible 行为 * * @default false */
focusVisible
?: boolean
/** * Prevent scrolling to the element when it is focused. * * @default false */
preventScroll
?: boolean
} export interface UseFocusReturn { /** * 如果为 true,则表示元素具有焦点。如果为 false,则表示元素没有焦点 * 如果设置为 true,则元素将获得焦点。如果设置为 false,则元素将失去焦点。 */
focused
:
WritableComputedRef
<boolean>
} /** * 跟踪或设置 DOM 元素的焦点状态。 * * @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

源码

源码演示文档

贡献者

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

更新日志

dd316 - feat: use passive event handlers everywhere is possible (#4477)
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)
4d868 - feat: support preventScroll option (#3994)