useFocus
一个响应式实用工具,用于跟踪或设置 DOM 元素的焦点状态。状态会随目标元素是否为焦点元素而改变。从外部设置响应式值将分别触发 focus 和 blur 事件,对应于 true 和 false 值。
演示
基本用法
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 的更改将分别自动触发 focus 和 blur 事件,对应于 true 和 false 值。您可以利用此行为将目标元素聚焦,作为另一个操作的结果(例如,如下所示的按钮点击)。
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">
Click me to focus input below
</button>
<input ref="input" type="text">
</div>
</template>类型声明
显示类型声明
ts
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