主题
useFocus
一个响应式工具,用于跟踪或设置 DOM 元素的焦点状态。状态变化会反映目标元素是否为当前焦点元素。从外部设置响应式值会分别触发 focus 和 blur 事件,针对 true 和 false 值。
🌐 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.
示例
基本用法
🌐 Basic Usage
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')
})设置初始焦点
🌐 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 = shallowRef()
const { focused } = useFocus(target, { initialValue: true })改变焦点状态
🌐 Change focus state
focused 响应式 ref 的变化将自动触发 focus 和 blur 事件,分别针对 true 和 false 值。你可以利用这种行为,将目标元素聚焦作为另一操作的结果(例如,如下所示的按钮点击)。
🌐 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 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>